Jimmery
Jimmery

Reputation: 10119

Disabling and greying out a UITextField in Swift

I have 2 UITextField's which I use for logging in. I want to temporarily disable them while the network request is made and then re-enable them once the network request is received.

I was hoping for the UITextField to be greyed out as well while they are disabled.

Here is the code for one of the UITextFields (they are both virtually identical, if I can disable one, then I can disable the other):

self.user = UITextField()
self.user.placeholder = "Username..."
self.user.keyboardType = UIKeyboardType.EmailAddress
self.user.frame = CGRectMake(20, 200, 300, 40)
self.view.addSubview(user)

I was hoping later in the code I could do something like:

self.user.enabled = false

But this doesn't seem to have any effect. Am I doing the right thing, and will this grey the UITextFields out?

Many thanks.

Upvotes: 1

Views: 4164

Answers (5)

eloka
eloka

Reputation: 105

Incase anyone else still needs the greying out effect you could just set the alpha property of the textfield e.g userTextfield.alpha = 0.3

Upvotes: 0

Marcelo Gracietti
Marcelo Gracietti

Reputation: 3131

for swift 3.0, correct command is:

myTextField.isUserInteractionEnabled = false

Upvotes: 1

Rodolfo Ocampo
Rodolfo Ocampo

Reputation: 1

You can also use UIApplication.sharedApplication().beginIgnoringInteractionEvents() so that everything in the View is ignored. Then use UIApplication.sharedApplication().endIgnoringInteractionEvents() to let the user continue to use the app.

Upvotes: 0

zisoft
zisoft

Reputation: 23078

You wrote: ... while the network request is made

UI changes must be made on the main thread, so you should make your network request on a background thread:

self.user.enabled = false

let bg_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

dispatch_async(bg_queue, {
    // your network request here...

    dispatch_async(dispatch_get_main_queue(), {
        self.user.enabled = true
    })
})

Upvotes: 2

Kirsteins
Kirsteins

Reputation: 27335

self.user.enabled = false should work. As you are doing a network call its very likely you are not executing this code from main thread (UIKit is not thread safe and should be updated only from main thread). Try the following code:

dispatch_async(dispatch_get_main_queue(), {
    self.user.enabled = false
});

This way the code will be dispatched to be executed on main thread.

Upvotes: 1

Related Questions