lakshmen
lakshmen

Reputation: 29064

Disabling a button in iOS

I need to disable a button if the key does not exist in the dictionary. I have used the setEnabled functionality of the UIButton but the image that has been set default still appears.

The code looks like this:

if([self.InfoDictionary objectForKey:ButtonExist])
{
    [button1 setEnabled:YES];
}
else
{
    [button1 setEnabled:NO];
}

The image still appears when I run in the simulator. Need some guidance on this.

Upvotes: 11

Views: 26793

Answers (5)

Yashesh
Yashesh

Reputation: 1752

Use:

if([self.InfoDictionary objectForKey:ButtonExist])
{
    [button1 setHidden:YES];
}
else
{
    [button1 setHidden:NO];
}

If you want to hide UIImage of UIButton then:

if([self.InfoDictionary objectForKey:ButtonExist])
    {
        [button1 setBackgroundImage:[UIImage imageNamed:@"YOUR IMAGE"] forState:UIControlStateNormal];
    }
    else
    {
        [button1 setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    }

Upvotes: 2

Jonghee Park
Jonghee Park

Reputation: 1275

in swift3:

self.button.isEnabled = false

Upvotes: 1

Seamus
Seamus

Reputation: 3191

Ran into this myself. The problem was that I was inadvertently enabling the button in a gesture handler for tap!

Look for side effects like this.

Upvotes: 0

Vinayak Kini
Vinayak Kini

Reputation: 2919

enable = YES property of button performs the action when clicked.

enable = NO property prevents action to be executed on click.

If you want to hide the button then you can set the hidden property as YES or vice versa. Other way to hide is by setting the alpha property to 0 (invisible) or 1 (visible)

Upvotes: 13

iPatel
iPatel

Reputation: 47049

Also you can set userInteractionEnabled property of UIButton

 if([self.InfoDictionary objectForKey:ButtonExist])
    {
        [button1 setEnabled:YES];
        button1.userInteractionEnabled = YES;
    }
    else
    {
        [button1 setEnabled:NO];
        button1.userInteractionEnabled = NO;
    }

Upvotes: 7

Related Questions