ios - 在 Swift 中实现用于选择的 UIButton

标签 ios iphone swift uibutton

我是 iOS 开发新手,正在开发一款消防安全应用。我想为用户提供 3 个风险级别的选项:低、中和高,方法是使用(我想)3 个用户可以点击的 UIButtons,他们点击的任何一个都会变成某种颜色。

我已经设法让 3 个 UIButtons 正常工作,它们可以在点击时改变颜色,但是如果我点击另一个按钮,我无法让前一个按钮变回原样,而且我很难为它们获取值(例如提交时,如果用户按下 Low,我会使用数字 2 进行计算)

为了展示这一点,我做了一个快速绘图: Button Example

感谢您的帮助:)

==== 编辑 ====

我现在使用分段控件而不是 UIButton 来执行此操作。但我需要知道如何在 if 语句中使用它们

@IBOutlet var RiskChoice: UISegmentedControl!
@IBOutlet var ValueLabel: UILabel!
@IBOutlet var CalcButton: UIButton!

@IBAction func Calculate(sender: UIButton) {

if (RiskChoice.selectedSegmentIndex == 0){
  ValueLabel.text = String("Low")
}

我设置的标签中没有任何内容。有人可以指引我到这里吗?

最佳答案

您可以在点击任何按钮时将所有 3 个按钮重置为默认状态,然后突出显示当前按钮。

@IBAction func buttonClicked(sender: UIButton) {

/** Reset all button to default state*/
resetAllButtons()

/** Highlight current button */
sender.backgroundColor = UIColor.redColor()
sender.titleColor = UIColor.whiteColor()
}


private func resetAllButtons() {

button1.backgroundColor = UIColor.clearColor()
button1.titleColor = UIColor.blackColor() /// Or use this : button1.setTitleColor(UIColor.blackColor, forState: .Normal)

button2.backgroundColor = UIColor.clearColor()
button2.titleColor = UIColor.blackColor()

button3.backgroundColor = UIColor.clearColor()
button3.titleColor = UIColor.blackColor()
}

关于ios - 在 Swift 中实现用于选择的 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38632419/

相关文章:

ios - 将数据附加到 TableView 单元格 展开可选值时出现 nil fatal error

ios - 使用 UserDefaults 保存图像数组

iphone - ASIHTTP请求超时

ios - 应用程序被终止后保持 Facebook 访问 iOS Swift

iphone - iPhone 5 + iOS6 将如何决定应用程序是否必须在信箱模式下运行

ios - 导航到 ViewController 并关闭 VC

objective-c - 延迟后的iOS设置属性

ios - 从其他类调用 Controller 函数

iphone - objective-c : How to highlight the first cell in table view when view loads?

ios - 使用 Swift 连接 SSH