使用titleLabel的UIButton动画子图层的子类

时间:2015-03-11 13:18:43

标签: ios swift uibutton subclass uicontrol

我正在创建UIButton的子类,在按钮层上有一个自定义子图层。

我在故事板中将此按钮设为System类型,只需在UIButton下的故事板中替换Identity inspector我的子类中的类。

我使用System类型按钮而不是自定义来获取titleLabel上的淡入淡出动画。

现在,我想淡化子图层以及titleLabel淡出时。

我尝试了begin/continue/endTrackingWithTouch:方法但是当titleLabel发生变化时它没有改变。

class TAButton:UIButton {
    let innerShadowLayer = CFInnerShadow() // Custom class of CAGradientLayer


    override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) -> Bool {
        innerShadowLayer.opacity = 0.5

        return super.beginTrackingWithTouch(touch, withEvent: event)
}
    override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) -> Bool {
        let con = super.continueTrackingWithTouch(touch, withEvent: event)
        println(con) // I expected this to change to false when titleLabel fades but I was wrong, its always true
        return con
    }
    override func endTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) {
        innerShadowLayer.opacity  = 1.0
        super.endTrackingWithTouch(touch, withEvent: event)
    }


    func setup() {
        self.setBackgroundGradient(UIColor(hex: 0x4A9BCB, alpha: 0.25), color2: UIColor(hex: 0xBAE5FF, alpha: 0.25)) // Custom function Im using
        self.makeRoundSides() // Custom function Im using

        innerShadowLayer.frame = self.bounds
        innerShadowLayer.cornerRadius = self.layer.cornerRadius
        innerShadowLayer.innerShadowRadius = 10
        innerShadowLayer.innerShadowOpacity = 0.6
        innerShadowLayer.innerShadowColor = UIColor(hex: 0x69FFF7, alpha: 1.0).CGColor
        self.layer.addSublayer(innerShadowLayer)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        setup()
    }
}

1 个答案:

答案 0 :(得分:0)

如果我覆盖touchesBegan和touchesEnded,这似乎对我有用。

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        super.touchesBegan(touches, withEvent: event)
        innerShadowLayer.opacity = 0.5
    }

    override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
        super.touchesEnded(touches, withEvent: event)
        innerShadowLayer.opacity = 1.0
    }