【问题标题】:Implementing UIButtons for selection in Swift在 Swift 中实现用于选择的 UIButton
【发布时间】:2016-07-28 09:31:47
【问题描述】:

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

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

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

感谢您的帮助:)

==== 编辑 ====

我现在使用分段控件而不是 UIButtons 来执行此操作。但我需要知道如何在 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")
}

我设置的标签中没有出现任何内容。有人可以在这里指导我吗?

【问题讨论】:

  • 请发布您已有的代码
  • 如果你没有任何限制,你可以使用segmented control...否则给一些你尝试过的代码
  • 如果您显示您尝试过的代码会更好,因为有很多方法可以做到这一点!
  • 好的,请参阅我的原始帖子以了解我所做的更改,现在只需要指向分段控件 :) @SuhasPatil

标签: ios iphone swift uibutton


【解决方案1】:

您可以在点击任何按钮时将所有 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()
}

【讨论】:

  • 这就是答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
  • 1970-01-01
  • 1970-01-01
  • 2017-07-03
  • 2015-01-28
相关资源
最近更新 更多