Swift3 如何处理“上的多个单选按钮”;addTarget";斯威夫特3.0?

Swift3 如何处理“上的多个单选按钮”;addTarget";斯威夫特3.0?,swift3,Swift3,当我通过for循环并使用功能addTarget创建多个单选按钮时,我如何在swift 3.0中通过标签或发送者使用addTarget处理多个单选按钮?以下是根据您的要求更改的解决方案 (SWIFT 4) //创建按钮数组以保存所有按钮 var buttonArray = [UIButton]() func createButtons(){ //create 5 buttons for i in 1...5 { let button = UIButton(fram

当我通过
for
循环并使用功能
addTarget
创建多个单选按钮时,我如何在swift 3.0中通过标签或发送者使用
addTarget
处理多个单选按钮?

以下是根据您的要求更改的解决方案 (SWIFT 4)

//创建按钮数组以保存所有按钮

var buttonArray = [UIButton]()

func createButtons(){
    //create 5 buttons
    for i in 1...5 {
        let button = UIButton(frame: CGRect(x: 0, y: i*55, width: 130, height: 50))
        //set same background for each button
        button.backgroundColor = UIColor.darkGray
        // set different ittle for button
        button.setTitle("Button No \(i)", for: .normal)
        // set different tag to differentiate betwwen button
        button.tag = i
        // set same target for each button
        button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
        buttonArray.append(button)
        //add all buttons to main view
        view.addSubview(button)

    }
    // we make first button of different color so that it can act as radio button
    let firstBtn = buttonArray[0]
    firstBtn.backgroundColor = UIColor.green
}


@objc func buttonTapped(_ tappedBtn : UIButton){
    // here we get tapped button so from array of button we match the selected one using tag and make it of different color all all other buttons of some different color
    for button in buttonArray {
        if(button.tag == tappedBtn.tag){
            button.backgroundColor = UIColor.green

        }else{
            button.backgroundColor = UIColor.darkGray
        }
    }

}