我有一个自定义的六边形按钮,我想禁用背景颜色,这样它就不会在六边形本身周围创建方形形状。
我正在使用 backgroundRect(forBounds:)
方法来覆盖背景的矩形。
这是完整的实现:
class HexaButton : UIButton {
var shape : CAShapeLayer!
func setup() {
if shape == nil {
shape = CAShapeLayer()
shape.fillColor = self.backgroundColor?.cgColor
shape.strokeColor = UIColor.cyan.cgColor
shape.lineWidth = 5.0
self.backgroundColor = UIColor.yellow
self.layer.addSublayer(shape)
}
let side : CGFloat = 6
let r = frame.height/side
shape.path = ShapeDrawer.polygonPath(x: frame.width/2, y: frame.height/2, radius: r, sides: Int(side), pointyness: side/2.0)
}
override func backgroundRect(forBounds bounds: CGRect) -> CGRect {
return .zero
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override func layoutSubviews() {
super.layoutSubviews()
setup()
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if shape?.path?.contains(point) == true {
return self
} else {
return nil
}
}
}
由于某种未知的原因,backgroundRect(forBounds:)
未被调用。
有什么想法吗?
最佳答案
您需要设置UIButton
的backgroundImage
属性,backgroundRect
方法将被调用。
关于ios - UIButton backgroundRect(forBounds :) not being called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39921284/