2014-12-03 67 views
0

我想创建一个UiTextView,只能输入50个字符,长度不应超过两行,并且按下返回键时关闭键盘。尝试使用基于许多stackover的各种方式,但似乎没有解决这个问题。不知道这样它是如此难以do.Any帮助将目前使用Swift UITextView

func textView(textView: UITextView!, shouldChangeTextInRange: NSRange, replacementText: NSString!){ 
if let range = text.rangeOfCharacterFromSet(NSCharacterSet.newlineCharacterSet()) { 
     println("start index: \(range.startIndex), end index: \(range.endIndex)") 
    } 
    else { 
     println("no data") 
    } 
} 
+0

[uitextview中字符数限制]的可能重复(http://stackoverflow.com/questions/2492247/limit-number-of-characters-in-uitextview) – 2014-12-03 15:40:28

回答

2

我不知道你所说的“长度不应超过两行”的意思来欣赏

,但我可以告诉你如何实现该委托方法,以将文本输入限制为50个或更少的字符。

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { 
    // range contains the range of text that is currently selected, this will be overwritten after this method returned true. If length is 0 nothing will be overwritten 
    // text contains the replacement text, might be the empty string "" which indicates deletion 

    // current text content of textView must be converted from String to NSString 
    // because stringByReplacingCharactersInRange(...) is a method on NSString 
    let currentText = textView.text as NSString 

    // do the changes that would happen if this method would return true 
    let proposedText = currentText.stringByReplacingCharactersInRange(range, withString: text) 
    if countElements(proposedText) > 50 { 
     // text would be longer than 50 characters after the changes are applied 
     // so ignore any input and don't change the content of the textView 
     return false 
    } 
    // go ahead and change text in the textView 
    return true 
} 

内联注释应解释所有必需的内容。

相关问题