UIButton 已禁用 - Swift

UIButton is disabled - Swift

我是 swift 编程的新手,我试图禁用保存按钮,直到选择了所有其他必需的按钮,但是当我尝试使用 button.isEnabled = false 执行此操作时,即使选择了所有按钮,它也不会改变。这是一个示例代码:

func disableButton () {
    if firstButton.isSelected && rightButton.isSelected  {
        saveButton.isEnabled = true
    } else {
        saveButton.isEnabled = false
    }
}

当我删除最后一行时,保存按钮有效,但当我将其放回去时,即使选择了其他两个按钮,它也被禁用。

假设您使用了 Storyboard,您必须将 2 个按钮 link 放入 @IBActions 中,并在这些 @IBAction 方法中操作 isSelected 属性。参考下面的例子。

注意 - 阅读评论

class ViewController: UIViewController {

    // 2 buttons that we will set the isSelected property
    @IBOutlet weak var button1: UIButton!
    @IBOutlet weak var button2: UIButton!

    // Button to disable/enable
    @IBOutlet weak var finalButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        finalButton.isEnabled = false // setting the button as disabled
    }

    /// This is the function triggered when you click on the "button1"
    @IBAction func didPressButton1(_ sender: UIButton) {
        // Here we will set the isSelected property of "sender" parameter, which is the button that calls this function. That is button 1
        sender.isSelected = sender.isSelected ? false : true
        //calling this function to make any updates to the UI if needed
        disableButton()
    }

    /// This is the function triggered when you click on the "button2"
    @IBAction func didPressButton2(_ sender: UIButton) {
        // Here we will set the isSelected property of "sender" parameter, which is the button that calls this function. That is button2
        sender.isSelected = sender.isSelected ? false : true
        //calling this function to make any updates to the UI if needed
        disableButton()
    }

    func disableButton () {
        if button1.isSelected && button2.isSelected  {
            finalButton.isEnabled = true
        } else {
            finalButton.isEnabled = false
        }
    }
}

这里发生的是你将在函数本身中设置调用函数的按钮的 isSelected 属性,并且每次都设置 运行 disableButton() 函数它被调用用于 UI 更新。 最终结果将是,