textFiled和 textView中限制输入字符长度(字符数)的方法(Swift/Xcode)


分别textFiled和 textView的代理方法中实现,如下:

1. textFiled中限制输入字符长度为6

 func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{

        if (range.location >= 6)

        {

                      return false//限制长度

        }     

        return true

    }

2. textView中限制输入字符长度为5

    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {

        if range.location >= 5{

        return false       

        }

        return true

    }

textView中还可以在这个方法中实现:

    func textViewDidChange(textView: UITextView) {

 

        if (100 - NSString(string: textView.text).length) < 0 {

            var str = textView.text

            let index1 = advance(str.endIndex, 100 - NSString(string: textView.text).length)

            self.textView.text = str.substringToIndex(index1)

        }

    }

 其他方法

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{

        var lengthOfString :NSInteger = count(string)

        var fieldTextString : String = textField.text

        var proposedNewLength : Int = count (fieldTextString) - range.length + lengthOfString;

        var maxNum = 15

        if (proposedNewLength > maxNum)

        {

            return false//限制长度

        }

        return true

    }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM