Enable a button in Swift only if all text fields have been filled out

前端 未结 10 785
误落风尘
误落风尘 2020-12-01 01:20

I am having trouble figuring out how to change my code to make it so the Done button in the navigation bar is enabled when my three text fields are filled out.

I cur

10条回答
  •  误落风尘
    2020-12-01 01:40

    why not move the checking functionality to a separate function

    func setDoneButtonStatus()
    {
        let habitNameText: NSString = (habitNameField.text!).stringByReplacingCharactersInRange(range, withString: string)
        let goalText: NSString = (goalField.text!).stringByReplacingCharactersInRange(range, withString: string)
        let frequencyText: NSString = (frequencyField.text!).stringByReplacingCharactersInRange(range, withString: string)
    
        doneBarButton.enabled = (habitNameText.length != 0) && (goalText.length != 0) && (frequencyText.length != 0)
    }
    

    and then use

    func textFieldShouldReturn(textField: UITextField) -> Bool
    {
        textField.resignFirstResponder()
        setDoneButtonStatus()
    }
    

提交回复
热议问题