Swift UIControlState.Selected 保持选中状态?

Swift UIControlState.Selected remain selected?

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

它们的定义如下:

 //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,我有另一个按钮,点击后会带你到另一个页面,但需要了解哪个按钮是 selected。

我尝试了以下操作,但它似乎无法识别 select 编辑了哪个按钮?

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

我是 swift 的新手,如有任何帮助,我们将不胜感激!

谢谢:)

您没有select点击按钮,您只是在更改图像。

首先,您可以简化所有代码并设置图像一次,灰色表示正常,彩色表示 selected 状态:

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) 
}

您也可以在 Storyboard 上配置它,也可以在图标的不同 State Configs 处更改 Image

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

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