自定义UI按钮未更改标题

时间:2018-10-11 08:37:13

标签: ios swift

我迅速为跟随按钮创建了一个自定义UI Button类,但是未显示按钮标题

我的代码

@IBDesignable
public class GradientButton: UIButton {

override public func layoutSubviews() {
    super.layoutSubviews()
    layoutGradientButtonLayer()
}

// MARK: Private
private func layoutGradientButtonLayer() {
    let layer = UIView()
    layer.frame = CGRect(x: 191, y: 257, width: 66.6, height: 24)
    let gradient = CAGradientLayer()
    gradient.frame = CGRect(x: 0, y: 0, width: 66.6, height: 24)
    gradient.colors = [
        UIColor(red: 0.09, green: 0.85, blue: 0.88, alpha: 1).cgColor,
        UIColor(red: 0, green: 0.87, blue: 0.68, alpha: 1).cgColor
    ]
    gradient.locations = [0, 1]
    gradient.startPoint = CGPoint(x: 0.78, y: 1)
    gradient.endPoint = CGPoint(x: 0.15, y: 1)
    self.layer.cornerRadius = 10
    self.layer.addSublayer(gradient)
    self.clipsToBounds = true
    self.setTitle("Follow", for: UIControlState.normal)

   }
  }

按钮显示为小宽度,并且其中没有任何“跟随”文本

1 个答案:

答案 0 :(得分:1)

更改以下代码,您将看到标题:

self.layer.addSublayer(gradient)

更改为

self.layer.insertSublayer(gradient, at: 0)

enter image description here