baiju krishnan
baiju krishnan

Reputation: 241

how to check title of uibutton

NSString *title=btn.titleLabel.text; 

NSLog(@"Title=%@",title); 

if(title == @"SelectCategory") 
{
    //alert    
}
else
{
    //somecode
}

I want to check title of UIButton. But my code always executing else statement.

What is the error in this code?

Upvotes: 0

Views: 3123

Answers (8)

Abhishek Singh
Abhishek Singh

Reputation: 6166

Two strings or two objects cannot be compared using ==. To compare two objects you should use isEqual.

In this case :

if([stringToBeCompared isEqualToString:@"comparestring"])
{
   //statement
}

Upvotes: 0

Prakash
Prakash

Reputation: 872

NSString *title=[btn currentTitle];

if([title isEqualToString:@"SelectCategory"])
{
  NSLog(@"Equal");
}

Upvotes: 3

Try this

UIButton *YourButton=btn;    

if([[YourButton titleForState:UIControlStateNormal] isEqualToString:@"SelectCategory"])
{
        // normal
}
else if([[YourButton titleForState:UIControlStateHighlighted] isEqualToString:@"SelectCategory"])
{
        //highlighted
}
else if([[YourButton titleForState:UIControlStateSelected] isEqualToString:@"SelectCategory"])
{
        //selected
}
else
{
        //somecode
}

Upvotes: 0

Krishnabhadra
Krishnabhadra

Reputation: 34275

Never compare two strings using '==', use isEqualToString

if ([title isEqualToString:@"SelectCategory"]){
   //alert
}else{
   //somecode
}

Upvotes: 4

Mat
Mat

Reputation: 7633

Never use == to compare strings, with == you're checking if the pointer of a string is the same of another string, and it's not what you want.

Upvotes: 0

iMash
iMash

Reputation: 1188

Try this line:

If([btn.titleLabel.text isEqualToString:@"Your text"])
{
//do this
}
else
{
//do this
}

Upvotes: 3

vishiphone
vishiphone

Reputation: 750

Use bun.title is Equalto:@"" it will work for you. Welcome

Upvotes: 0

taskinoor
taskinoor

Reputation: 46027

Use

if ([title isEqualToString:@"SelectCategory"]) {}

instead of == operator.

Upvotes: 1

Related Questions