最新消息:服务器现已从linode换到fzhost.net,且主题已从retina 0.2换为大前端D8

[已解决]swift中动态判断文本框输入的内容决定是否允许输入

Swift crifan 27浏览 0评论

[背景]

需要对于文本框来说,超过11位之后,就不允许继续输入了

搜:

swift textfield input change

swift textfield input change not allow

ios – Allow only Numbers for UITextField input – Stack Overflow

但是:

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let allow = true
        if let inputText = textField.text {
            let updatedStr:String = inputText.stringByReplacingCharactersInRange(range, withString: string)
            print("updatedStr=\(updatedStr)")
        }
       
        return allow
    }

却出错:

Cannot convert value of type ‘NSRange’ (aka ‘_NSRange’) to expected argument type ‘Range<Index>’ (aka ‘Range<String.CharacterView.Index>’)

去搜:

swift textfield shouldChangeCharactersInRange

ios – How shouldChangeCharactersInRange works in Swift? – Stack Overflow

ios – Textfield shouldchangecharactersinrange swift – Stack Overflow

ios – UITextView shouldChangeCharactersInRange in Swift – Stack Overflow

 How to program an iOS text field that takes only numeric input or specific characters with a maximum length [Updated for Swift 2] — Global Nerdy – Joey deVilla’s mobile/tech blog

最后用代码:

class RegisterPhoneViewController: UIViewController, UITextFieldDelegate {
        phoneTextField.delegate = self
   functextField(textField:UITextField, shouldChangeCharactersInRange range:NSRange, replacementString string:String) ->Bool{
        var allow = true
        print("range=\(range), string=\(string)")
        if let inputText = textField.text {
            let updatedStr:String = (inputText as NSString).stringByReplacingCharactersInRange(range, withString: string)
            print("updatedStr=\(updatedStr)")
           
            if updatedStr.characters.count > 11 {
                allow = false
            }
        }
       
        return allow
    }

实现了效果:

一直输入,直到输入了11位数字,再多就不允许输入了:

range=(0,0), string=1
updatedStr=1
range=(1,0), string=3
updatedStr=13
range=(2,0), string=8
updatedStr=138
range=(3,0), string=1
updatedStr=1381
range=(4,0), string=2
updatedStr=13812
range=(5,0), string=3
updatedStr=138123
range=(6,0), string=4
updatedStr=1381234
range=(7,0), string=5
updatedStr=13812345
range=(8,0), string=6
updatedStr=138123456
range=(9,0), string=7
updatedStr=1381234567
range=(10,0), string=8
updatedStr=13812345678
range=(11,0), string=0
updatedStr=138123456780
range=(11,0), string=0
updatedStr=138123456780

如图:

转载请注明:在路上 » [已解决]swift中动态判断文本框输入的内容决定是否允许输入

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
57 queries in 0.623 seconds, using 12.88MB memory