我认为我关于按钮的代码违反了枯燥原则。你能提出一个更有效的方法来减少杂乱吗?
@IBAction func competitiveButton(_ sender: Any) {
if competitiveMatch.isEnabled == true {
competitiveMatch.isEnabled = false
friendlyMatch.isEnabled = true
tournamentButton.isEnabled = true
trainingButton.isEnabled = true
} else {
competitiveMatch.isEnabled = true
}
}
@IBAction func friendlyButton(_ sender: Any) {
if friendlyMatch.isEnabled == true {
friendlyMatch.isEnabled = false
tournamentButton.isEnabled = true
competitiveMatch.isEnabled = true
trainingButton.isEnabled = true
} else {
friendlyMatch.isEnabled = true
}
}
@IBAction func tourneyButton(_ sender: Any) {
if tournamentButton.isEnabled == true {
tournamentButton.isEnabled = false
friendlyMatch.isEnabled = true
trainingButton.isEnabled = true
competitiveMatch.isEnabled = true
} else {
tournamentButton.isEnabled = true
}
}
@IBAction func trainingButton(_ sender: Any) {
if trainingButton.isEnabled == true {
trainingButton.isEnabled = false
friendlyMatch.isEnabled = true
tournamentButton.isEnabled = true
competitiveMatch.isEnabled = true
} else {
trainingButton.isEnabled = true
}
}
该代码遵循所有四个按钮的设置模式。我不能用更短的方法来做同样的事情。请帮帮忙。这里完全是初学者。
发布于 2018-06-20 15:46:08
您可以使用单个IBAction
,而不是4个单独的方法。并使发送方类型从UIButton
到Any
。然后你可以做一些类似的事情
@IBAction func toggleEnableDisable(_ sender: UIButton) {
let currentValue = sender.isEnabled
let buttonArray = [trainingButton, friendlyMatch, tournamentButton, competitiveMatch]
buttonArray.forEach { $0.isEnabled = false }
sender.isEnabled = !currentValue
}
https://stackoverflow.com/questions/50950970
复制相似问题