-1

我是 obj-c 的新手,我正在尝试编写一个简单的 IBAction,其中一旦单击按钮就会更改其标签。它适用于图像背景和静态字符串,但是当它崩溃时:

int i = (arc4random()%90);
NSString *lab = [NSString stringWithFormat:@"%d", i];
[sender setText:lab];

为什么?提前ty

编辑:这是整个方法

-(IBAction) toggleUIButtonImage:(id)sender{
    NSString *img = @"bulldog-cute-tom-bancroft.jpg";
    NSString *imgSel = @"kitten-cute-tom-bancroft.jpg";
    UIImage *unselectedImage = [UIImage imageNamed:img];
    UIImage *selectedImage = [UIImage imageNamed:imgSel];
    if ([sender isSelected]) {
        [sender setBackgroundImage:unselectedImage forState:UIControlStateNormal];
        [sender setSelected:NO];
    }else {
        [sender setBackgroundImage:selectedImage forState:UIControlStateSelected];
        [sender setSelected:YES];
    }

    int i = (arc4random()%90);
    NSString *lab = [NSString stringWithFormat:@"%d", i];
    [sender setTitle:lab forState: UIControlStateNormal];

} 
4

3 回答 3

2

这不是随机 int 或 int2str 转换。这是您设置按钮文本的方式。使用它,它应该可以工作:

[sender setTitle: lab forState: UIControlStateNormal]; 

(当然,如果 sender 实际上是 UIButton 的话)

编辑:

UIButton *button = (UIButton *)sender; 

为此,还建议您使用从发送者到 UIButton*(或您想要响应该方法的任何其他特定类)的强制转换,以确保您使用正确的类方法。

于 2012-07-10T10:32:05.147 回答
2

您正在尝试设置 UIButton 的标题。为此,您需要使用setTitle:forState:而不是setText.

[sender setTitle:lab  forState:UIControlStateNormal];

UIButton 参考:UIButton

编辑:如果senderid类型,将其更改为 UIButton ,如:

UIButton *b = (UIButton *)sender;

或简单地更改方法签名,例如:

-(IBAction) toggleUIButtonImage:(UIButton *)sender
于 2012-07-10T10:33:11.130 回答
0

您应该通过 Interface Builder 设置对按钮的引用,例如: @property (strong, nonatomic) UIButton *buttonName;

或从 IBAction 方法获取按下它的按钮: UIButton *buttonName = (UIButton *)sender;

无论哪种方式,您都可以使用以下语法设置 UIButton 的标题文本: [buttonName setTitle:lab forState:UIControlStateNormal];

于 2015-08-18T15:50:01.933 回答