Labels properties changing in Xcode

63 views Asked by At

I have written this code to change colour of different labels through different buttons
I am new to app development, just got stuck up in pretty basics:

-(IBAction)ButtonPressed:(id)sender
{
    UIButton *btn=sender;

    if(btn.tag==1)
    {
        lbl1.text=@"";
        lbl1.backgroundColor=[UIColor redColor];
    }
    if(btn.tag==2)
    {
        lbl2.text=@"";
        lbl2.backgroundColor=[UIColor greenColor];
    }
    else if(btn.tag==3)
    {
        lbl3.text=@"";
        lbl3.backgroundColor=[UIColor magentaColor];
    }
    else if(btn.tag==4)
    {
        lbl4.text=@"";
        lbl4.backgroundColor=[UIColor blueColor];
    }
    else if(btn.tag==5)
    {
        lbl5.text=@"";
        lbl5.backgroundColor=[UIColor brownColor];
    }
}

After writing the code the colour of label one is only getting changed. I have connected all the elements through storyboard though

2

There are 2 answers

1
Omer Waqas Khan On

Try it like this

-(IBAction)ButtonPressed:(id)sender
    {
        NSInteger i = [sender tag];

        if(i==1)
        {
            lbl1.text=@"";
            lbl1.backgroundColor=[UIColor redColor];
        }
        if(i==2)
        {
            lbl2.text=@"";
            lbl2.backgroundColor=[UIColor greenColor];
        }
        else if(i==3)
        {
            lbl3.text=@"";
            lbl3.backgroundColor=[UIColor magentaColor];
        }
        else if(i==4)
        {
            lbl4.text=@"";
            lbl4.backgroundColor=[UIColor blueColor];
        }
        else if(i==5)
        {
            lbl5.text=@"";
            lbl5.backgroundColor=[UIColor brownColor];
        }
    }

Or Simply

-(IBAction)ButtonPressed:(id)sender
    {
        if([sender tag]==1)
        {
            lbl1.text=@"";
            lbl1.backgroundColor=[UIColor redColor];
        }
        if([sender tag]==2)
        {
            lbl2.text=@"";
            lbl2.backgroundColor=[UIColor greenColor];
        }
        else if([sender tag]==3)
        {
            lbl3.text=@"";
            lbl3.backgroundColor=[UIColor magentaColor];
        }
        else if([sender tag]==4)
        {
            lbl4.text=@"";
            lbl4.backgroundColor=[UIColor blueColor];
        }
        else if([sender tag]==5)
        {
            lbl5.text=@"";
            lbl5.backgroundColor=[UIColor brownColor];
        }
    }

Also check the tags of the buttons.

0
Kishore Suthar On

Only replace this line UIButton *btn=sender;

with UIButton *btn = (UIButton *)sender;