12

我试图找出在以下代码中按下 UIButton 的 UIButton 标题是什么。

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

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

我想在按下按钮时获得这个标题。

谢谢你的帮助

:)

// 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);

        }
4

3 回答 3

28

在你的行动中:

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

编辑:或如评论 Iulian:,sender.currentTitle但可能是nil,请参阅 Michael 的评论。

于 2013-01-07T15:52:15.717 回答
11

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

- (void)buttonPressed:(id)sender

把这个放在里面...

- (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);
}
于 2013-01-07T15:50:45.133 回答
4
NSString * strButtonTitle = [btnButton titleForState:state];

其中状态:

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

为您的要求

NSString * strButtonTitle = [btnButton titleForState:UIControlStateSelected];

这是在程序中的任何给定时间获取按钮不同状态标题的方法......但基于Zaphod的问题答案是好的。

于 2016-06-30T07:17:36.887 回答