ios - UIButton backgroundRect(forBounds :) not being called

标签 ios uibutton

我有一个自定义的六边形按钮,我想禁用背景颜色,这样它就不会在六边形本身周围创建方形形状。 我正在使用 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:) 未被调用。 有什么想法吗?

最佳答案

您需要设置UIButtonbackgroundImage 属性,backgroundRect 方法将被调用。

关于ios - UIButton backgroundRect(forBounds :) not being called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39921284/

相关文章:

ios - 为什么 UIButton 在以编程方式调用其处理程序时不更改其图像?

ios - 如何在 Objective-C 中旋转 UIButton 和 UILabel 的文本?

ios - 核心数据查询返回正确的值,但表格单元格为空

ios - 如何在 Swift 中创建序列?

ios - 自定义 iPhone 相机控件(不使用 UIImagePickerController)

iphone - iPhone 上的 UIButton —— 使按钮摇动或摆动

用于无线分发的 iOS4 企业应用程序

ios - iOS 上的夏至日期

ios - 检测在 UITableView 中按下了哪个 UIButton

iphone - 在 GridView 中按下哪个按钮