Getting title of UIButton in event handler

前端 未结 4 1570
囚心锁ツ
囚心锁ツ 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:40
    -(void)clicketbutton {
        UIButton *mybutton = [UIButton buttonWithType:UIButtonTypeCustom];
        [mybutton setTitle:@"Click here"  forState:UIControlStateNormal];
        [mybutton addTarget:self  
           action:@selector(displayvalue:)forControlEvents:UIControlEventTouchUpInside]; 
    }
    -(void)displayvalue:(id)sender {       
    
         NSLog(@"The title is %@ ", [mybutton titleForState:UIControlStateNormal]);
    
    }
    
    0 讨论(0)
  • 2020-12-29 04:42

    Your displayvalue: method should look something like this:

    -(void)displayvalue:(id)sender {       
        UIButton *resultButton = (UIButton *)sender;
        NSLog(@" The button's title is %@.",  resultButton.currentTitle);
    }
    

    (Please check out the documentation in XCode, it would have given you the right answer.)

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-29 05:01
    -(void)displayvalue:(id)sender 
    {
        UIButton *resultebutton= (UIButton*)sender;
        NSLog(@"The button title is %@ ", resultebutton.titleLabel.text);
    }
    
    0 讨论(0)
提交回复
热议问题