Getting title of UIButton in event handler

前端 未结 4 1657
囚心锁ツ
囚心锁ツ 2020-12-29 04:02

I create a button and set title as \"Click here\". When I press that button I want to get that button title and log it. Here\'s my code, where am I going wrong?



        
4条回答
  •  半阙折子戏
    2020-12-29 04:44

    I know it's a bit of an old question, but this is probably the neatest way to resolve this one.

    NSLog(@"The button title is: %@", [sender currentTitle]);        
    

    Edit
    I've just realised that this is depending on the fact that you have set the receiving parameter to UIButton*. Rather than using the default id, creating a UIButton object and casting (id)sender to that button. Cut out the middle man and just set the function signature to

    -(void)buttonPressed:(UIButton*)sender{
      NSLog(@"Button title: %@",sender.currentTitle);
    }  
    

    This is effectively casting the function parameter

提交回复
热议问题