iOS中的CustomView和CustomButton

时间:2016-04-28 21:26:49

标签: ios swift

我创建了两个自定义类:CutomView类(UIView的子类)和CustomButton类(UIButton的子类)。

class CustomView: UIView {

    override func drawRect(rect: CGRect) {
        // Drawing code
        layer.masksToBounds = true
        layer.borderWidth = 2.0
        layer.borderColor = UIColor(colorLiteralRed: 0.0/255, green: 64.0/255, blue: 128.0/255, alpha: 1).CGColor
        layer.cornerRadius = 10.0
        let startColor = UIColor(colorLiteralRed: 255.0/255, green: 204.0/255, blue: 1.0, alpha: 1.0).CGColor
        let endColor = UIColor(colorLiteralRed: 0, green: 128.0/255, blue: 1.0, alpha: 1.0).CGColor
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = CGRect(origin: layer.frame.origin, size: layer.frame.size)
        gradientLayer.colors = [startColor, endColor];
        layer.addSublayer(gradientLayer)
    }

@IBDesignable
class CustomButton: UIButton {
    override func drawRect(rect: CGRect) {
        // Drawing code
        layer.masksToBounds = true
        layer.borderWidth = 2.0
        layer.borderColor = UIColor(colorLiteralRed: 0.0/255, green: 64.0/255, blue: 128.0/255, alpha: 1).CGColor
        layer.cornerRadius = 2.0
        let startColor = UIColor(colorLiteralRed: 192.0/255, green: 192.0/255, blue: 192.0/255, alpha: 1.0).CGColor
        let endColor = UIColor(colorLiteralRed: 239.0/255, green: 239.0/255, blue: 239.0/255, alpha: 1.0).CGColor
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = CGRect(origin: layer.frame.origin, size: layer.frame.size)
        gradientLayer.colors = [startColor, endColor];
        layer.addSublayer(gradientLayer)
    }

}

我使用这些自定义子类来设计视图和按钮。当我查看应用的自定义类时,它们工作正常,但由于某些原因,该按钮在模拟器或iOS设备中不可见。

如果有人能指出我或帮我解决它会很棒。

Storyboard and Preview shows the purple blue background and button

Simulator only displays purple blue background

1 个答案:

答案 0 :(得分:0)

您的layer.addSublayer调用会将图层附加到图层层次结构中。因此,渐变是最后绘制的,有效地绘制自定义按钮。您希望渐变为背景,因此请确保它是第一个绘制的图层。变化

layer.addSublayer(gradientLayer)

layer.insertSublayer(gradientLayer, atIndex: 0)