方向改变后自定义UIButton背景

时间:2016-06-19 06:25:02

标签: ios swift2

学习斯威夫特。 我有一个UIButton课程。这是它:

class CustomBtn: UIButton {
    var shadowLayer: CAShapeLayer!
    var shadowAdded: Bool = false

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!

    }

    override func layoutSubviews() {
        super.layoutSubviews()

    }


    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        super.drawRect(rect)

        shadowLayer                 = CAShapeLayer()
        shadowLayer.path            = UIBezierPath(roundedRect: bounds, cornerRadius: 5).CGPath
        shadowLayer.fillColor       = UIColor(netHex: Colors.Red1.value).CGColor
        shadowLayer.shadowColor     = UIColor.darkGrayColor().CGColor
        shadowLayer.shadowPath      = shadowLayer.path
        shadowLayer.shadowOffset    = CGSize(width: 2.0, height: 2.0)
        shadowLayer.shadowOpacity   = 0.8
        shadowLayer.shadowRadius    = 2

        layer.insertSublayer(shadowLayer, atIndex: 0)
    }
}

这是我的输出:

enter image description here

但是当我改变方向时:

enter image description here

如何让按钮背景(红色和阴影)以任何方向填充宽度?

1 个答案:

答案 0 :(得分:1)

您实际上并不需要覆盖drawRect,因此最好注意上面评论中的建议。但是,问题是您是根据按钮的边界设置图层路径,但是当您旋转设备时这些边界会发生变化,但您没有更新图层。

您尝试实现的许多效果也可以通过设置按钮图层本身的属性来完成。我会把你的班级改为:

class CustomBtn: UIButton {

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        self.commonInit()
    }

    override init(frame:CGRect){
        super.init(frame: frame)
        self.commonInit()
    }

    func commonInit(){

        self.layer.backgroundColor = UIColor(netHex: Colors.Red1.value).CGColor
        self.layer.cornerRadius    = 5

        self.layer.shadowColor     = UIColor.darkGrayColor().CGColor
        self.layer.shadowOffset    = CGSize(width: 2.0, height: 2.0)
        self.layer.shadowOpacity   = 0.8
        self.layer.shadowRadius    = 2
    }
}

通过添加commonInit

,您可以让您的课程更高效
    self.layer.shadowPath      = UIBezierPath(roundedRect: bounds, cornerRadius: 5).CGPath

但如果你这样做,你还想添加:

   override var bounds: CGRect{
        didSet{
            self.commonInit()
        }
    }

因此,只要边界发生变化,您的阴影路径就会更新。