未调用UIButton backgroundRect(forBounds :)

时间:2016-10-07 15:51:18

标签: 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:)未被调用。 任何想法?

1 个答案:

答案 0 :(得分:1)

您需要设置 CUT V1 1: (6.57e+04,6.6e+04] 45493 2: (6.6e+04,6.63e+04] 77865 3: (6.66e+04,6.69e+04] 22893 4: (6.75e+04,6.78e+04] 61738 5: (6.54e+04,6.57e+04] 44805 6: (6.69e+04,6.72e+04] 64079 7: NA 33234 8: (6.72e+04,6.75e+04] 66517 9: (6.63e+04,6.66e+04] 43887 10: (6.78e+04,6.81e+04] 172 的{​​{1}}属性,并调用backgroundImage方法。