biggreentree biggreentree - 3 months ago 12
iOS Question

Setting maximum number of characters of `UITextView ` and `UITextField `

I'd like to set a maximum number of characters allowed to be typed both in a

UITextView
and a
UITextField
. This number will be then shown in a little label (for user's reference, Twitter Style.)

I'm sure I'm missing something about properties to both Views.

I started with:

class NewChatsFromHomeVC: UIViewController, UITextFieldDelegate {

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


then, I checked on stackOverflow and I found this and this, in
viewDidLoad
but I don't know where I'm wrong:

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

var shouldChange = false

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

return shouldChange
}


Abhinav's answer:

I have:

class NewChatsFromHomeVC: UIViewController, CLLocationManagerDelegate, UITextViewDelegate {


then:

@IBOutlet weak var startingMessageTextView: UITextView!


then in
viewDidLoad()


startingMessageTextView.delegate = self


finally, as independent func, outside of
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;
}


but got this errors:

on
self.startingMessageTextView


Expected parameter type following ':'

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

Answer

Try this out:

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;
}
Comments