ios - 应用渐变后获取透明 UIButton
问题描述
我正在通过尝试开发一个应用程序来学习 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
}()
实际上,它应该说登录(白色)带有蓝色到绿色的渐变层。如果我将登录标题颜色设置为黑色。当我运行代码时,我可以看到它。
解决方案
推荐阅读
- jquery - jQuery:向内联样式函数添加重要内容
- python - 使用 make install 的 Ambertools20 编译错误
- javascript - 上传图片时如何添加额外的 CSS?以及如何让用户只对突出显示的内容进行粗体/斜体/下划线?
- javascript - 如何在 React 中单击按钮时显示和隐藏元素?
- bash - Bash:如何在系统范围内限制文件大小或设置为更大的值?
- python - 谷歌云运行上的烧瓶舞Facebook登录错误
- python - 无法让 2 个不同的正则表达式查找器调用在 Python 的循环中工作
- mongodb - 使用 $near/$geoNear 未获得结果 - 嵌套位置对象中的 GeoJSON
- php - 如何在单个帖子页面中查询以获取当前自定义帖子的值?
- javascript - 如何在axios中渲染数字/整数?