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

2024-04-20

我试图找出在以下代码中按下 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);

        }

在你的行动中:

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

Edit: 或者正如尤利安评论的那样:sender.currentTitle,但也可能是nil,请参阅迈克尔的评论。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在按下 UIButton 时获取其标题 的相关文章

随机推荐