如何在警报文本字段中将数字输入设置为 20000 数字 SWIFT


    let alertController = UIAlertController(title: "Interval Mode", message: "Please input 20 to 20000 ms", preferredStyle: .alert)
    let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (_) in
        let txtMiliSecond = alertController.textFields?[0]
    }
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }
    alertController.addTextField {
            (textField) in textField.placeholder = "Enter 20 to 20000 ms";
            textField.keyboardType = .numberPad
    }

您需要在文本字段中的文本更改时添加目标

 alertController.addTextField { (textField : UITextField!) -> Void in
        textField.placeholder = "Enter Reason"
        textField.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: .editingChanged)
        self.saveAction.isEnabled = false
    }

然后,在文本字段更改时执行某些操作。

 func textFieldDidChange(_ textField: UITextField) {
    if(textField.text?.isEmpty == true){
        //Disable Button
        saveAction.isEnabled = false
    }else{
        //Enable button
        saveAction.isEnabled = true
    }
}

在此示例中,我根据文本字段启用/禁用保存按钮

  func textField(_ textField: UITextField, shouldChangeCharactersIn 
   range: NSRange, replacementString string: String) -> Bool {
    if(textField.tag == 1 && self.isDigit(string) == true){
        let maxLength = 5
        let newLength = (textField.text?.characters.count)! + 
          string.characters.count - range.length
        return newLength <= maxLength
    }
    else if (textField.tag == 2){
        let maxLength = 16
        guard let text = textField.text
            else{
            return true
        }
        let newLength = text.characters.count + 
         string.characters.count - range.length
        return newLength <= maxLength
    }
    return false
}

将标签编号设置为文本字段。

最新更新