[我为UIButton创建了一个自定义类,该类也使用@IBInspectable来为按钮添加圆角和阴影。
现在,我想使用相同的按钮为个人资料图像选择器创建一个圆形。用户点击圆形按钮,将显示照片库,用户选择一张照片,然后将所选图像添加到圆形按钮。
我的问题是,用户选择图像后,按钮的imageView是正方形而不是圆形。
我已经尝试使用按钮的imageView的图层,并尝试将其设置为clipsToBounds或maskToBounds,但是我想我缺少了一些东西。
以下是不包含ImageView内容的自定义按钮的代码:
import UIKit
class RoundShadowButton: UIButton {
override init(frame: CGRect){
super.init(frame: frame)
imageView?.clipsToBounds = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
imageView?.clipsToBounds = true
}
@IBInspectable
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
}
}
@IBInspectable
var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
@IBInspectable
var borderColor: UIColor? {
get {
let color = UIColor.init(cgColor: layer.borderColor!)
return color
}
set {
layer.borderColor = newValue?.cgColor
}
}
@IBInspectable
var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
layer.shadowRadius = newValue
}
}
@IBInspectable
var shadowOffset : CGSize{
get{
return layer.shadowOffset
}set{
layer.shadowOffset = newValue
}
}
@IBInspectable
var shadowColor : UIColor{
get{
return UIColor.init(cgColor: layer.shadowColor!)
}
set {
layer.shadowColor = newValue.cgColor
}
}
@IBInspectable
var shadowOpacity : Float {
get{
return layer.shadowOpacity
}
set {
layer.shadowOpacity = newValue
}
}
}
我认为您会丢失,除非您为按钮设置图像,否则按钮的imageView
为nil
。您应该将maskToBounds
设置为按钮,或者在设置图像后将其设置为imageView。另外,请检查您的拐角半径,如果您有基于框架的方法,则在自动布局期间,您可以基于.zero
框架设置拐角半径