swift设置最大的 'UITextView' 和 'UITextField' 字符数

发布时间: 2016/2/27 16:45:26
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我想设置最大允许字符数要键入两个在 UITextViewUITextField 。这一数字将然后显示在小小的标签 (供用户参考,推特风格。)

我敢肯定我遗漏有关这两个视图的属性。

我开始用:

class NewChatsFromHomeVC: UIViewController, UITextFieldDelegate {

@IBOutlet weak var myMessageTextView: UITextView!
@IBOutlet weak var myMessageObjectLabel: UITextField!
@IBOutlet weak var myCharRemainingLabel: UILabel!

然后,我查看了一下计算器,我发现这个这个,在 viewDidLoad ,但我不知道我在哪里错了:

textField(textField: myMessageTextView!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {

                var shouldChange = false

                if countElements(textField.text) < 10 {
                    shouldChange = true
                }

                return shouldChange
        }

板球的答案:

我有:

class NewChatsFromHomeVC: UIViewController, CLLocationManagerDelegate, UITextViewDelegate {

然后:

@IBOutlet weak var startingMessageTextView: UITextView!

然后在viewDidLoad()

startingMessageTextView.delegate = self

最后,作为独立的 func,外面的viewDidLoad():

func textView(textView: UITextView , shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    let newText = (textView.text as NSString).stringByReplacingCharactersInRange(range, withString: text)
    let numberOfChars = count(newText) // for Swift use count(newText) //Swift2 newText.characters.count
    return numberOfChars < 10;
}

但有此错误:

关于self.startingMessageTextView

Expected parameter type following ':'

NewChatsFromHomeVC.swift:82:33: Expected ',' separator

解决方法 1:

尝试一下:

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    let newText = (textView.text as NSString).stringByReplacingCharactersInRange(range, withString: text)
    let numberOfChars = newText.characters.count // for Swift use count(newText)
    return numberOfChars < 10;
}
官方微信
官方QQ群
31647020