Swift UIControlState.Selected保持选中状态?

时间:2015-11-06 16:12:07

标签: swift button ibaction control-state

我有3个按钮,提供给用户以选择他们希望看到的类别。

它们的定义如下:

 //outlets
@IBOutlet weak var ChineseButton: UIButton!
@IBOutlet weak var IndianButton: UIButton!
@IBOutlet weak var MexicanButton: UIButton!

我在这些按钮上有以下操作(将原始图像按钮更改为灰色版本):

//动作

@IBAction func ChineseButtonPressed(sender: UIButton)
{

    ChineseButton.setImage(UIImage(named: "chinese.png"), forState: UIControlState.Normal)
    ChineseButton.setImage(UIImage(named: "chinese.png"), forState: UIControlState.Selected)
    IndianButton.setImage(UIImage(named: "grey-indian.png"), forState: UIControlState.Normal)
    MexicanButton.setImage(UIImage(named: "grey-mexican.png"), forState: UIControlState.Normal)

}
@IBAction func EightFacedButtonPressed(sender: UIButton) {
         IndianButton.setImage(UIImage(named: "indian.png"), forState: UIControlState.Normal)
IndianButton.setImage(UIImage(named: "indian.png"), forState: UIControlState.Selected)
    ChineseButton.setImage(UIImage(named: "grey-chinese.png"), forState: UIControlState.Normal)

    MexicanButton.setImage(UIImage(named: "grey-mexican.png"), forState: UIControlState.Normal)
}

@IBAction func TweleveFacedButtonPressed(sender: UIButton) {
    MexicanButton.setImage(UIImage(named: "mexican.png"), forState: UIControlState.Normal)
MexicanButton.setImage(UIImage(named: "mexican.png"), forState: UIControlState.Selected)
    ChineseButton.setImage(UIImage(named: "grey-chinese.png"), forState: UIControlState.Normal)
    IndianButton.setImage(UIImage(named: "grey-indian.png"), forState: UIControlState.Normal)   
}

此动作功能也决定了UIControlState,我有另一个按钮,一旦点击它将带你到另一个页面,但需要了解选择了哪个按钮。

我尝试了以下但是它似乎无法识别选择了哪个按钮?

 @IBAction func GenerateButton(sender: UIButton) {
        if ChineseButton.selected == true{
            println("Chinese button was selected")
        }

我是swift的新手,所以任何帮助都会受到赞赏!

谢谢:)

1 个答案:

答案 0 :(得分:1)

您没有选择按钮,只是在更改图像。

首先,您可以简化所有代码并将图像设置为一次,灰色显示正常,并为选定状态着色:

override func viewDidLoad() {
    super.viewDidLoad()

    MexicanButton.setImage(UIImage(named: "mexican.png"), forState: UIControlState.Normal)
    MexicanButton.setImage(UIImage(named: "grey-mexican.png"), forState: UIControlState.Selected)
    ChineseButton.setImage(UIImage(named: "grey-chinese.png"), forState: UIControlState.Normal)
    ChineseButton.setImage(UIImage(named: "chinese.png"), forState: UIControlState.Selected)
    IndianButton.setImage(UIImage(named: "grey-indian.png"), forState: UIControlState.Normal)
    IndianButton.setImage(UIImage(named: "indian.png"), forState: UIControlState.Selected) 
}

您可以在故事板上配置此功能,并在图标的不同Image处更改State Configs

enter image description here

然后,在每个动作上,您只需选择按钮,就会显示正确的图像(您可以对所有按钮使用相同的动作):

@IBAction func AnyButtonPressed(sender: UIButton) {
    // Deselect all buttons but the pressed one
    for button in [ChineseButton, IndianButton, MexicanButton] {
        button.selected = sender === button
    }
}