Reputation: 429
I am trying to create a UiTextView that only can enter in 50 characters and should not be more than two lines in length and when the return is pressed close the keyboard.Tried various ways based on many stackover but none seem to fix the issue. Not sure way it has to be so hard to do.Any help would be appreciate
Currently using
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")
}
}
Upvotes: 0
Views: 2359
Reputation: 90127
I'm not sure what you mean by "should not be more than two lines in length", but I can show you how you can implement that delegate method to limit text entry to 50 or less characters.
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
}
The inline comments should explain everything that's necessary.
Upvotes: 2