如何在按下UIButton时获取UIButton的标题

han*_*Dev 11 iphone objective-c uibutton ios

我试图在下面的代码中发现UIButton的UIButton标题是什么.

在viewDidLoad上,使用以下命令将按钮标题输出到控制台:

        NSLog(@"The button title is %@ ", btn.titleLabel.text);
Run Code Online (Sandbox Code Playgroud)

我想在按下按钮时获得此标题.

谢谢你的帮助

:)

// Create buttons for the sliding category menu.
        NSMutableArray* buttonArray = [NSMutableArray array];
        NSArray * myImages = [NSArray arrayWithObjects:@"category-cafe-unsel.png", @"category-food-unsel.png", @"category-clothing-unsel.png", @"category-health-unsel.png", @"category-tech-unsel_phone.png" , @"category-tech2-unsel.png", @"catefory-theatre-unsel.png", @"category-travel-unsel.png", nil];

        // only create the amount of buttons based on the image array count
        for(int i = 0;i < [myImages count]; i++)
        {
            // Custom UIButton

            btn = [UIButton buttonWithType:UIButtonTypeCustom];

            [btn setFrame:CGRectMake(0.0f, 20.0f, 52.0f, 52.0f)];
            [btn setTitle:[NSString stringWithFormat:@"Button %d", i] forState:UIControlStateNormal];
            [btn setImage:[UIImage imageNamed:[myImages objectAtIndex:i]] forState:UIControlStateNormal];

            NSLog(@"The button title is %@ ", btn.titleLabel.text);

            [btn addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
            [buttonArray addObject:btn];

            NSLog(@"Button tag is: %d",btn.tag);

        }
Run Code Online (Sandbox Code Playgroud)

Zap*_*hod 24

在你的行动中:

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

编辑:或者作为评论Iulian:,sender.currentTitle但可能是nil,请参阅迈克尔的评论.


Fog*_*ter 11

你应该在某个地方有这个功能......

- (void)buttonPressed:(id)sender
Run Code Online (Sandbox Code Playgroud)

把它放在里面......

- (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);
}
Run Code Online (Sandbox Code Playgroud)