gpt4 book ai didi

ios - Xcode/Swift 为所有同名按钮添加渐变层

转载 作者:行者123 更新时间:2023-11-28 12:37:19 25 4
gpt4 key购买 nike

Xcode/Swift 如此新颖,我正在为应用程序中不同 View Controller 中的一堆按钮添加渐变层。我想知道是否有一种方法可以同时定位所有具有特定名称的按钮,而不是将我的代码单独添加到每个页面中。这是我的渐变代码:

let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.btnSavePhoto.bounds

let color1 = UIColor(red:0.05, green:0.29, blue:0.49, alpha: 1.0).CGColor as CGColorRef
let color2 = UIColor(red:0.08, green:0.23, blue:0.39, alpha: 1.0).CGColor as CGColorRef

gradientLayer.colors = [color1, color2]

gradientLayer.locations = [0.0, 1.0]

self.btnSavePhoto.layer.addSublayer(gradientLayer)

最佳答案

您可以创建一个自定义类,使您的 UIButton 像这样以某种方式带有渐变

对于 Swift 3

import UIKit

public class GradientButton: UIButton {

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

// MARK: Private
private func layoutGradientButtonLayer() {
let gradientLayer = CAGradientLayer()
let color1 = UIColor(red:0.05, green:0.29, blue:0.49, alpha: 1.0).cgColor as CGColor
let color2 = UIColor(red:0.08, green:0.23, blue:0.39, alpha: 1.0).cgColor as CGColor
gradientLayer.colors = [color1, color2]
gradientLayer.locations = [0.0, 1.0]
self.layer.addSublayer(gradientLayer)
}
}

对于 Swift 2.3

import UIKit

public class GradientButton: UIButton {

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

// MARK: Private
private func layoutGradientButtonLayer() {
let gradientLayer = CAGradientLayer()
let color1 = UIColor(red:0.05, green:0.29, blue:0.49, alpha: 1.0).CGColor as CGColorRef
let color2 = UIColor(red:0.08, green:0.23, blue:0.39, alpha: 1.0).CGColor as CGColorRef
gradientLayer.colors = [color1, color2]
gradientLayer.locations = [0.0, 1.0]
self.layer.addSublayer(gradientLayer)
}
}

然后在按钮的检查器中,您可以将类设置为 GradientButton 检查图像

enter image description here

这样你就不需要为渐变按钮编写代码了。

关于ios - Xcode/Swift 为所有同名按钮添加渐变层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40492231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com