Nathan McKaskle Nathan McKaskle - 1 year ago 188
iOS Question

UITextView shouldChangeCharactersInRange in Swift

Trying to disable/enable the next button (which begins disabled on the storyboard) based on how many characters are in the textView field. It isn't working, which makes me think that only the textField has this feature and not the textView (they were really lazy with developing the textView field).

I have an outlet connected for the textView and next button:

@IBOutlet weak var textView: UITextView!
@IBOutlet weak var nextButton: UIBarButtonItem!

func textView(textView: UITextView, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

let oldText: NSString = textView.text
let newText: NSString = oldText.stringByReplacingCharactersInRange(range, withString: string)

if newText.length > 0 {

nextButton.enabled = true

} else {

nextButton.enabled = false

return true


How do I get this to work, because it just completely ignores it even if it compiles without errors.

Answer Source

Requires UITextViewDelegate reference in class line:

class MyViewController: UIViewController, UITextViewDelegate {


AND it also requires a referencing outlet from the view controller to the textView delegate. Select the view controller, click on outlets, drag from referencing outlet to the textView, click delegate.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download