开发者

How to get tag of clicked UIButton Without IB?

Can anyone tell me that How to get tag of a UIButton when i click on it...

I have made 5 buttons having tag 1,2,3,4 & 5 resp.(all are calling same method getTag )

and i tried following ways for that method

- Methgod-1

-(void)getTag{ //I know that this will never work }

- Methgod-2

-(void)getTag:(id)sender{ //Unable to access sender.tag property }

- Methgod-3

-(void)getTag:(UIButton*)sender{ //Program crashes }

开发者_如何学运维

I am not using IB please help.....


Both method-2 and -3 can be correct - in method 2 you only need to cast sender to UIButton explicitly, e.g:

-(void)getTag:(id)sender{ 
    UIButton *btn = (UIButton*)sender;
    switch (btn.tag){
     ...
    } 
}

Possible reason why method 1 works and 2and 3 not is wrong selector you assign to your button action. For method 1 it should be

@selector(getTag)

For second

@selector(getTag:); // NOte ':' in selector which denotes that method gets 1 parameter


Use method 2 and code as follows,

UIButton *button = (UIButton *)sender;



button.tag;


UIButton * myB = [[UIButton alloc]init];

myB.tag = 2;

NSLog(@"TAG=%i",myB.tag);

//OUTPUT: 'TAG=2'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜