首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >代码重构- Swift

代码重构- Swift
EN

Stack Overflow用户
提问于 2018-06-20 14:45:12
回答 1查看 203关注 0票数 0

我认为我关于按钮的代码违反了枯燥原则。你能提出一个更有效的方法来减少杂乱吗?

代码语言:javascript
运行
复制
@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
    }
}

该代码遵循所有四个按钮的设置模式。我不能用更短的方法来做同样的事情。请帮帮忙。这里完全是初学者。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-20 15:46:08

您可以使用单个IBAction,而不是4个单独的方法。并使发送方类型从UIButtonAny。然后你可以做一些类似的事情

代码语言:javascript
运行
复制
@IBAction func toggleEnableDisable(_ sender: UIButton) {
    let currentValue = sender.isEnabled
    let buttonArray = [trainingButton, friendlyMatch, tournamentButton, competitiveMatch]
    buttonArray.forEach { $0.isEnabled = false }
    sender.isEnabled = !currentValue
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50950970

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档