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

时间:2015-01-18 17:52:42

标签: ios swift uialertcontroller

我找到了关于如何为UIAlertController 添加文本字段的示例代码,但我无法限制用户只输入10个字符作为限制< / strong>,当编辑为常规文本字段更改无法检查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)

谢谢。

1 个答案:

答案 0 :(得分:8)

您可以将警报控制器的文本字段的委托设置为 例如,这里显示https://stackoverflow.com/a/24852979/1187415

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

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

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

然后实现shouldChangeCharactersInRange委托方法, 每当文本即将被更改时调用 用户互动。它可以返回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
}

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