当用户使用 swift 键入时,限制 UIAlertController 中文本字段的输入?

Restrict the input of a textfield in UIAlertController when the user types using swift?

我找到了关于如何为 UIAlertController 添加文本字段 的示例代码,但我无法限制用户输入只有 10 个字符作为限制,当常规文本字段的编辑更改无法完成时,我有一个删除最后一个字符的功能检查 UIAlertController.

上的文本字段
//Function to Remove the last character

func trimStr(existStr:String)->String{

    var countExistTextChar = countElements(existStr)

    if countExistTextChar > 10 {
        var newStr = ""
        newStr = existStr.substringToIndex(advance(existStr.startIndex,(countExistTextChar-1)))
        return newStr

    }else{
        return existStr
    }

}

 var inputTextField: UITextField?

    //Create the AlertController
    let actionSheetController: UIAlertController = UIAlertController(title: "Alert", message: "Swiftly Now! Choose an option!", preferredStyle: .Alert)

    //Create and add the Cancel action
    let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
        //Do some stuff
    }
    actionSheetController.addAction(cancelAction)
    //Create and an option action
    let nextAction: UIAlertAction = UIAlertAction(title: "Next", style: .Default) { action -> Void in


    }
    actionSheetController.addAction(nextAction)
    //Add a text field
    **actionSheetController.addTextFieldWithConfigurationHandler { textField -> Void in
        //TextField configuration
        textField.textColor = UIColor.blueColor()

        inputTextField = textField**


    }

    //Present the AlertController
    self.presentViewController(actionSheetController, animated: true, completion: nil)

谢谢。

您可以将警报控制器的文本字段的 delegate 设置为 例如这里显示 :

actionSheetController.addTextFieldWithConfigurationHandler { [weak self] textField -> Void in
    //TextField configuration
    textField.textColor = UIColor.blueColor()
    textField.delegate = self
}

请注意,您必须将 UITextFieldDelegate 协议添加到您的 查看控制器定义以进行编译:

class ViewController: UIViewController, UITextFieldDelegate {
    // ...

然后你实现shouldChangeCharactersInRange委托方法, 每当文本将要响应更改时调用 到用户交互。它可以 return truefalse 允许 改变或拒绝它。

在中有各种如何限制文本字段长度的示例 这个委托方法,这是一种可能的实现方式:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange,
    replacementString string: String) -> Bool {
        let newString = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string) as NSString
        return newString.length <= 10
}

这将导致输入被忽略,如果它会导致文本字段 长度大于 10。或者你总是可以截断 输入10个字符:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange,
    replacementString string: String) -> Bool {
        let newString = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)
        textField.text = trimStr(newString)
        return false
}

第二种方法的缺点是光标总是跳动 到文本字段的末尾,即使在某处插入了文本 介于两者之间。