obj-c连接int问题

时间:2012-07-10 10:24:33

标签: iphone objective-c cocoa concatenation

我是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];

} 

3 个答案:

答案 0 :(得分:2)

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

[sender setTitle: lab forState: UIControlStateNormal]; 

(即如果发件人当然是UIButton)

编辑:

UIButton *button = (UIButton *)sender; 

建议从发件人到UIButton *(或任何其他您希望对该方法做出响应的特定类)的强制转换,以确保您使用正确的类方法。

答案 1 :(得分:2)

您正在尝试设置UIButton的标题。 为此,您需要使用setTitle:forState:代替setText

[sender setTitle:lab  forState:UIControlStateNormal];

UIButton参考:UIButton

编辑: 如果sender是一种 id ,请将其更改为UIButton,如:

UIButton *b = (UIButton *)sender;

或只是更改方法签名,如:

-(IBAction) toggleUIButtonImage:(UIButton *)sender

答案 2 :(得分:0)

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

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

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