Greg
Greg

Reputation: 427

Disable editing of a text field

I want to start by saying this is my first project and I am trying hard to find answers myself before posting here. I thought I had found the code to accomplish this. I have no errors but when I run, the field is still editable. So, how can I disable editing of my field when the rule I have set is true?

if sport.count == 1 {

        enterSport.text = sport[0] as String //need to convert to a string
        enterSport.editing; false //do not allow editing

    } else {
        //do nothing
    }

I have defined the array previously so the if statement is true. Thank you for you assistance.

Upvotes: 12

Views: 33189

Answers (4)

Alirza Eram
Alirza Eram

Reputation: 178

There is one more way of avoiding keyboard appearing

You can set an UITapGestureRecognizer like this:

let tap = UITapGestureRecognizer(target: self, action: #selector(self.textFieldEditing))
self.enterSport.addGestureRecognizer(tap)

and

@objc func textFieldEditing() {
    self.enterSport.resignFirstResponder()
    
}

Upvotes: 1

Dima
Dima

Reputation: 23624

enterSport.userInteractionEnabled = false instead of editing.

editing is a read-only property to indicate if the field is currently being edited or not.

Swift 5: enterSport.isUserInteractionEnabled = false

Upvotes: 24

cylov
cylov

Reputation: 128

With Swift 3 Apple changed the property userInteractionEnabled to isUserInteractionEnabled.

The code looks like this:

textfield.isUserInteractionEnabled = true

Upvotes: 4

Duncan C
Duncan C

Reputation: 131398

To summarize the answers and comments above:

editing is a readonly property. You can't set it.

If it's a UITextView, it has an editable property which you can set to false.

If it's a UITextField, you need to use the enabled property or the userInteractionEnabled property. Either of those will prevent editing. As

Upvotes: 4

Related Questions