UIButton选定状态并存储值

时间:2018-10-19 09:15:00

标签: ios swift

嘿,我是iOS开发的新手,我有一个问题要使两个按钮处于选中状态和未选中状态,然后存储性别值。我想当用户选择性别时,其他性别将被禁用。谁能帮我吗?

我的按钮代码

let menButton: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Men", for: .normal)
    button.setTitleColor(.white, for: .normal)
    button.backgroundColor = .yellow
    button.isSelected = false
    button.isEnable = true
    button.addTarget(self, action: #selector(handlePickGender), for: .touchUpInside
    return button
}()

let womenButton: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Women", for: .normal)
    button.setTitleColor(.white, for: .normal)
    button.backgroundColor = .blue
    button.isSelected = false
    button.isEnable = true
    button.addTarget(self, action: #selector(handlePickGender), for: .touchUpInside
    return button
}() 

3 个答案:

答案 0 :(得分:0)

首先,为性别创建enum,并将男性和女性添加为该enum的案例。

enum Gender {
  case male
  case female
 }

具有用于切换UIButton状态的开关。

func chooseGender(_ gender: Gender) {

   switch gender {
     case .male:
        // code for select and unselect
     case .female:
        // code for select and unselect
    }
}

UIButton中,使用isEnabled属性启用和禁用。

答案 1 :(得分:0)

如果您要创建切换按钮。

您可以设置按钮图像的状态。

button.setImage(UIImage(named: "unselected"), for: .normal)
button.setImage(UIImage(named: "selected"), for: .selected)


@IBAction func buttonPressed(sender: UIButton) {
    button.selected = !button.selected
}

或者您可以为按钮设置背景颜色

@IBAction func buttonPressed(sender: UIButton) {
        button.selected = !button.selected
        if button.selected {
             button.backgroundColor = .blue
        } else {
             button.backgroundColor = .clear
        }
}

答案 2 :(得分:0)

尝试一下:

@objc func handlePickGender(sender: UIButton) {
        menButton.setTitleColor(UIColor.yellow, for: .normal)
        womenButton.setTitleColor(UIColor.yellow, for: .normal)
        sender.setTitleColor(UIColor.blue, for: .normal)
        //store gender
        let selectedGender = sender.title(for: .normal)
   }