gpt4 book ai didi

ios - Swift 创建 UIButton 和 UIView 颜色更改的通用扩展

转载 作者:行者123 更新时间:2023-11-29 05:22:34 24 4
gpt4 key购买 nike

就我而言,我正在尝试创建多个按钮。在这里,每个按钮都放置在单独的 UIView 上。该按钮的工作方式类似于基于选择的单个部分。我在每个按钮 acton 方法中更改其标题颜色和 UIView 颜色。在这里,我需要为所有按钮标题和 UIView 颜色更改创建一个通用扩展。一旦单击按钮,需要将值传递给扩展或函数来更改选择按钮的颜色。这是我试图减少代码重复和 LOC。

注意: 下面我只发布了一个按钮代码,但我有很多按钮。我想将其设为公共(public)类并传递值来更改颜色。如何实现这一目标?

第一个按钮操作

 @IBAction func firstButtonClick(_ sender: Any) {
self.onetimeView.backgroundColor = colorLiteral(red: 0.184337255, green: 0.683529412, blue: 0.976475882, alpha: 1)
self.dailyView.backgroundColor = colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
self.weeklyView.backgroundColor = colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
self.fiftydaysView.backgroundColor = colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
self.monthlyView.backgroundColor = colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)

self.onetimeButton.setTitleColor(UIColor.selectedColor, for: .normal)
self.dailyButton.setTitleColor(UIColor.disabledColor, for: .normal)
self.weeklyButton.setTitleColor(UIColor.disabledColor, for: .normal)
self.fiftydaysButton.setTitleColor(UIColor.disabledColor, for: .normal)
self.monthlyButton.setTitleColor(UIColor.disabledColor, for: .normal)
}

@IBAction func secondButtonClick(_ sender: Any) {
self.onetimeView.backgroundColor = colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
self.dailyView.backgroundColor = colorLiteral(red: 0.184337255, green: 0.683529412, blue: 0.976475882, alpha: 1)
self.weeklyView.backgroundColor = colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
self.fiftydaysView.backgroundColor = colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
self.monthlyView.backgroundColor = colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)

self.onetimeButton.setTitleColor(UIColor.disabledColor, for: .normal)
self.dailyButton.setTitleColor(UIColor.selectedColor, for: .normal)
self.weeklyButton.setTitleColor(UIColor.disabledColor, for: .normal)
self.fiftydaysButton.setTitleColor(UIColor.disabledColor, for: .normal)
self.monthlyButton.setTitleColor(UIColor.disabledColor, for: .normal)
}

extension UIColor {
static var selectedColor = UIColor.init(red: 47/255, green: 174/255, blue: 248/255, alpha: 1)
static var disabledColor = UIColor.init(red: 170/255, green: 170/255, blue: 170/255, alpha: 1)
}

最佳答案

您可以创建一个子类,例如:

类 PrimaryButton: UIButton {}

关于ios - Swift 创建 UIButton 和 UIView 颜色更改的通用扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58524237/

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