ios - UIButton 就像一个单选按钮
问题描述
我需要像单选按钮一样创建按钮。我试着改变颜色。当我单击其中一个按钮时,所有其他按钮都变为灰色。但它们不会将颜色更改为灰色。
extension UIView {
func setGradientBackground(colorOne: UIColor, colorTwo: UIColor, cornerRadius: CGFloat) {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.bounds
gradientLayer.colors = [colorOne.cgColor, colorTwo.cgColor]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
gradientLayer.cornerRadius = cornerRadius
layer.insertSublayer(gradientLayer, at: 10)
}
}
@IBAction func oneButtonAction(_ sender: Any) {
oneButton.setGradientBackground(colorOne: UIColor(red: 0, green: 0.52, blue: 1, alpha: 1), colorTwo: UIColor(red: 0, green: 0.39, blue: 0.81, alpha: 1), cornerRadius: oneButton.frame.height/2)
twoButton.backgroundColor = UIColor(red: 0.94, green: 0.96, blue: 0.98, alpha: 1)
}
@IBAction func twoButtonAction(_ sender: Any) {
oneButton.backgroundColor = UIColor(red: 0.94, green: 0.96, blue: 0.98, alpha: 1)
twoButton.setGradientBackground(colorOne: UIColor(red: 0, green: 0.52, blue: 1, alpha: 1), colorTwo: UIColor(red: 0, green: 0.39, blue: 0.81, alpha: 1), cornerRadius: oneButton.frame.height/2)
}
解决方案
首先使用单个操作分配所有按钮。
然后将您要作为单选组执行的所有按钮放在一个数组中。
let buttonGroup: [UIButton] = [button1, button2, button3]
@IBAction func buttonAction(_ sender: UIButton) {
buttonGroup.forEach { button in
if button == sender {
button.setGradientBackground(colorOne: UIColor(red: 0, green: 0.52, blue: 1, alpha: 1), colorTwo: UIColor(red: 0, green: 0.39, blue: 0.81, alpha: 1), cornerRadius: oneButton.frame.height/2)
} else {
button.backgroundColor = UIColor(red: 0.94, green: 0.96, blue: 0.98, alpha: 1)
}
}
}
推荐阅读
- php - 如何在不重新登录的情况下重新加载会话
- python - PyTorch:将词向量加载到字段词汇表与嵌入层
- android - React Native - Android 模拟器设备
- python - 如何在 Python 中使用 RegEx 术语过滤迭代不同列表的文本?
- javascript - 从服务器获取数据时挂载的钩子(Promise/async)出错
- python - 代码在 VS Code 中运行,但不在终端中
- shell - 使用 find 在不同目录中调用具有多个输入参数的 shell 脚本
- r - 在 R 中重新分类栅格
- python - 19 位时间戳转换
- flutter - 动画时无法消除溢出错误。(颤动)