简体   繁体   English

Swift Button.setText不适用于渐变

[英]Swift Button.setText doesn't work with gradient

I'm new in Swift and I have a problem. 我是Swift的新手,我遇到了问题。 my button do not set the text if I try to use the gradient. 如果我尝试使用渐变,我的按钮不会设置文本。 here is my code: 这是我的代码:

let gradient:CAGradientLayer = CAGradientLayer()
    let colorBottom = UIColor(red: 9/255.0, green: 137/255.0, blue: 133/255.0, alpha: 1.0).CGColor
    let colorTop = UIColor(red: 222.0/255.0, green: 255.0/255.0, blue: 201.0/255.0, alpha: 1.0).CGColor

    gradient.colors = [colorTop, colorBottom]
    gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
    gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
    gradient.frame = LoginButton.bounds
    gradient.cornerRadius = 25.0


    LoginButton.layer.addSublayer(gradient)
    LoginButton.setTitle("Login", forState: UIControlState.Normal)
    LoginButton.setTitleColor(UIColor.blackColor(), forState: .Normal)


    self.view.addSubview(LoginButton)

Adding a sublayer works the same as adding a subview so adding the gradient layer may be covering the other layers where the text is drawn. 添加子图层与添加子视图的工作方式相同,因此添加渐变图层可能会覆盖绘制文本的其他图层。

If you remove this line does it work? 如果删除此行,它是否有效?

LoginButton.layer.addSublayer(gradient)

If it does, try seeing how many layers are in LoginButton.layer.sublayers and try inserting the gradient layer behind one of those sublayers (wherever it looks the best) using one of the following methods: 如果是这样,请尝试查看LoginButton.layer.sublayers有多少层,并尝试使用以下方法之一将渐变层插入其中一个子层(无论它看起来最好)的后面:

-insertSublayer:above:
-insertSublayer:below:
-insertSublayer:atIndex:

This line is the problem: 这一行是问题所在:

LoginButton.layer.addSublayer(gradient)

Do not add any extra layers to a UIButton. 不要向UIButton添加任何额外的图层。 It already knows how to draw itself. 它已经知道如何绘制自己。 If you want it to have a gradient background, draw the gradient into an image and set that as the button's background image in the normal way. 如果您希望它具有渐变背景,请将渐变绘制到图像中,并以正常方式将其设置为按钮的背景图像。

Or make the button clear and put the gradient layer behind the button (though this is not as good). 或者清除按钮并将渐变层放在按钮后面 (虽然这不是很好)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM