如何制作它以便无法点击按钮,直到文本框中包含文字?

时间:2015-11-30 16:45:48

标签: swift button

所以到目前为止我有这个

{
    nextNounOutlet.enabled = false
    super.viewDidLoad()
}

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textfieldNoun.text != "" {
      nextNounOutlet.enabled = false
    }
    return true
}

我想这样做,以便无法点击nextNounOutlet按钮,直到某些内容被放入文本框中,但它不会起作用。这样,它将永远保持禁用状态。我已经尝试过添加其他声明,但这不会起作用,也不会改变真假。 任何建议,我都使用swift。

2 个答案:

答案 0 :(得分:4)

您需要修改代码,使其不是单行道":目前,一旦shouldChangeCharactersInRange方法禁用按钮,代码中就没有任何内容可以重新启用它

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    // Get the text after applying the update
    var txtAfterUpdate:NSString = self.textfieldNoun.text as NSString
    txtAfterUpdate = txtAfterUpdate.stringByReplacingCharactersInRange(range, withString: string)
    // Enable or disable the button based on the length of the updated text
    nextNounOutlet.enabled = (txtAfterUpdate.length != 0)
}

答案 1 :(得分:1)

@dasblinkenlight的回答应该对你有用,如果没有,你可以通过编程方式重新解决问题。

在ViewDidLoad中,您可以向textFields添加目标:

 self.firstNameField.addTarget(self, action: "textFieldChanged:", forControlEvents: .EditingChanged)
 self.lastNameField.addTarget(self, action: "textFieldChanged:", forControlEvents: .EditingChanged)

然后创建一个动作:

func textFieldChanged(sender: UITextField) {
    // simple validation
    if firstNameField.text?.characters.count > 0
        && lastNameField.text?.characters.count > 0 {
            self.createButton.enabled = true // re-enable your button
    }
}