我有一个UIButton
,当我按下它时我想切换标题和颜色。按钮应该有三种状态:每日,每月和每年。
现在我有这个看起来不那么优雅的解决方案:
if sender.currentTitle == "Daily" {
sender.setTitle("Monthly", for: .normal)
sender.setTitleColor(UIColor(hex: "FB967F"), for: .normal)
} else if sender.currentTitle == "Monthly" {
sender.setTitle("Yearly", for: .normal)
sender.setTitleColor(UIColor(hex: "A395CE"), for: .normal)
} else if sender.currentTitle == "Yearly" {
sender.setTitle("Daily", for: .normal)
sender.setTitleColor(UIColor(hex: "75CFF8"), for: .normal)
}
在Swift中有更方便的方法吗?
答案 0 :(得分:5)
使用枚举 这是维持国家的最佳选择。保持您的代码超级干净和可读。
enum ButtonState {
case daily
case monthly
case yearly
mutating func next(forButton button:UIButton) {
switch (self) {
case .daily:
self = .monthly
case .monthly:
self = .yearly
case .yearly:
self = .daily
}
button.setTitle(self.getTitle(), forState: .Normal)
button.setTitleColor(UIColor(hex: self.getTitleColorHex()), forState: .Normal)
}
private func getTitle() -> String {
switch (self) {
case .daily:
return "Daily"
case .monthly:
return "Monthly"
case .yearly:
return "Yearly"
}
}
private func getTitleColorHex() -> String {
switch (self) {
case .daily:
return "FB967F"
case .monthly:
return "A395CE"
case .yearly:
return "75CFF8"
}
}
}
var currentButtonState = ButtonState.daily
func changeButtonState(forButton button:UIButton) {
currentButtonState.next(forButton: button)
}
答案 1 :(得分:1)
声明counter
变量和两个数组
var counter = 0
let titleArray = ["Daily", "Monthly", "Yearly"]
let colorArray = ["FB967F", "A395CE", "75CFF8"]
然后递增计数器(通过模运算符将其保持在0 ... 2范围内)并从数组中获取标题和颜色值
counter = (counter + 1) % titleArray.count
sender.setTitle(titleArray[counter], for: .normal)
sender.setTitleColor(UIColor(hex: colorArray[counter]), for: .normal)
答案 2 :(得分:-1)
我真的不认为你的代码是所以不优雅 - 三态不是那么复杂以至于难以阅读(这实际上是代码不雅的问题),但是,如果它超过三个你肯定想要更整洁的东西。如何使用状态转换字典:
func newButtonState(sender: UIButton) {
let buttonDict = ["Yearly": (UIColor.red, "Daily"),
"Monthly": (UIColor.green, "Yearly"),
"Daily": (UIColor.yellow, "Monthly")]
if let t = sender.currentTitle, let n: (UIColor, String) = buttonDict[t] {
sender.setTitle(n.1, for: .normal)
sender.setTitleColor(n.0, for: .normal)
}
}