How to get the title for a UIButton when it is pressed

后端 未结 3 1614
日久生厌
日久生厌 2021-02-19 23:08

I\'m trying to discover what the UIButton title is for which UIButton was pressed in the following code.

on viewDidLoad the button title is outputted to the console usin

相关标签:
3条回答
  • 2021-02-19 23:18
    NSString * strButtonTitle = [btnButton titleForState:state];
    

    where state:

    UIControlStateNormal,
    UIControlStateHighlighted,
    UIControlStateDisabled,
    UIControlStateSelected,
    UIControlStateFocused,
    UIControlStateApplication,
    UIControlStateReserved
    

    For your requirement

    NSString * strButtonTitle = [btnButton titleForState:UIControlStateSelected];
    

    This is the method for getting the title for different states of button at any given time in the program...But based on the question answer from Zaphod is good.

    0 讨论(0)
  • 2021-02-19 23:31

    In your action:

    - (void) buttonPressed:(UIButton*) sender {
        NSLog(@"The button title is %@",sender.titleLabel.text);
    }
    

    Edit: Or as commented Iulian: sender.currentTitle, but it may be nil, see the comments of Michael.

    0 讨论(0)
  • 2021-02-19 23:31

    You should have the function somewhere...

    - (void)buttonPressed:(id)sender
    

    Just put this inside it...

    - (void)buttonPressed:(id)sender
    {
        UIButton *someButton = (UIButton*)sender;
    
        NSLog(@"The button title is %@ ", [someButton titleForState:UIControlStateNormal]);
    
        //You should also be able to use...
        //NSLog(@"The button title is %@ ", someButton.titleLabel.text);
    }
    
    0 讨论(0)
提交回复
热议问题