user3483697
user3483697

Reputation: 123

UITextView() cannot be defined as nil?

I am trying to implement a method to move the scrollview so the textview isn't blocked by the keyboard. As a part of the standard code, the UITextView needs to be set to nil but it's not working.

I first declared

var activeTextView = UITextView()

then

    func textFieldDidEndEditing(textView: UITextView) {
    self.activeTextView = nil
    scrollView.scrollEnabled = false
}

xcode shows an error saying, UITextView does not conform to NilLiteralConvertible. Why?

Upvotes: 0

Views: 446

Answers (2)

Michael Voznesensky
Michael Voznesensky

Reputation: 1618

Your answer is not correct! It is not because it needs to be a UIView. Both UITextView and UITextField are subclasses of UIView, and you are using the wrong one.

You want either this from the textFieldDelegate:

func textFieldDidEndEditing(textField: UITextField)

https://developer.apple.com/Library/ios/documentation/UIKit/Reference/UITextFieldDelegate_Protocol/index.html

or this from the textViewDelegate

func textViewDidEndEditing(textView: UITextView)

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextViewDelegate_Protocol/index.html

The reason yours worked with UIView is because both subclass it, but that does not make it correct!

Upvotes: 1

Dennis Weidmann
Dennis Weidmann

Reputation: 1967

If I understand your Question right, you just need to declear your TextView as an optional, because in Swift you cant set an non optional Object to nil.

var activeTextView: UITextView?

Should solve your Problem.

The Questionmark will declear it as an optional and only an optional could be nil.

Upvotes: 0

Related Questions