ios - 应用渐变后获得透明的 UIButton

标签 ios swift xcode swift4

我正在通过尝试开发一个应用程序来学习Swift。我想通过添加渐变层来设计一个按钮,但问题是它没有出现在屏幕上。当我单击它应该出现的位置时,它就会发挥作用。

extension UIColor {
    convenience init(red: Int, green: Int, blue: Int) {
        assert(red >= 0 && red <= 255, "Invalid red component")
        assert(green >= 0 && green <= 255, "Invalid green component")
        assert(blue >= 0 && blue <= 255, "Invalid blue component")

        self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}

convenience init(rgb: Int) {
    self.init(
        red: (rgb >> 16) & 0xFF,
        green: (rgb >> 8) & 0xFF,
        blue: rgb & 0xFF
    )
}

}

extension UIButton
{
    func applyGradient(colors: [CGColor])
{
       let gradientLayer = CAGradientLayer()
       gradientLayer.colors = colors
       gradientLayer.startPoint = CGPoint(x: 0, y: 0)
       gradientLayer.endPoint = CGPoint(x: 1, y: 1)
       gradientLayer.frame = self.bounds
       self.layer.addSublayer(gradientLayer)
}

lazy var loginButton: UIButton = {
    let button = UIButton(type: .system)
    let color1 = UIColor(red: 26, green: 41, blue: 128)
    let color2 = UIColor(red: 38, green: 208, blue: 206)
    button.applyGradient(colors: [color1.cgColor, color2.cgColor]) 
    button.setTitle("Log in", for: .normal)
    button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
    button.setTitleColor(.black, for: .normal)

    button.addTarget(self, action: #selector(handleButtonLogin), for: .touchUpInside)

    return button
}()

实际上,它应该说登录(白色),带有蓝色到绿色的渐变层。如果我将登录标题颜色设置为黑色。当我运行代码时我可以看到它。

最佳答案

你只是错过了框架

loginButton.frame = self.view.frame
self.view.addSubview(loginButton) 
loginButton.applyGradient(colors: [UIColor.red.cgColor,UIColor.blue.cgColor])

//

同时更改此行

self.layer.addSublayer(gradientLayer)

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

不要隐藏按钮的标题

//

enter image description here

关于ios - 应用渐变后获得透明的 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51656001/

相关文章:

ios - 从 iOS 8.0.2 到 8.1,录制的高 fps 视频文件有何变化?

ios - 如何将对象添加到数组?

ios - 从 firebase 中检索金额值使用 swift 3 进行减法和更新金额

xcode - 无法使用类型为 '(String)' 的参数列表调用 <method>

ios - 更改包标识符会导致应用程序在模拟器中失败

ios - 如何使用 node.js 保护我的 api,并且只有我的应用程序正在使用此 api

ios - 在 Parse 上存储信息

ios - CompileSwiftSources 正常 x86_64 com.apple.xcode.tools.swift.compiler

xcode - 为什么会出现Apple Mach-O Linker(ID)错误?

ios - 在 Objective-C 中使用 #define 并在 swift 类中访问