我创建了两个自定义类: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
答案 0 :(得分:0)
您的layer.addSublayer
调用会将图层附加到图层层次结构中。因此,渐变是最后绘制的,有效地绘制自定义按钮。您希望渐变为背景,因此请确保它是第一个绘制的图层。变化
layer.addSublayer(gradientLayer)
到
layer.insertSublayer(gradientLayer, atIndex: 0)