【问题标题】:Add one to integer displayed in UILabel将 UILabel 中显示的整数加一
【发布时间】:2011-07-29 20:56:11
【问题描述】:

我有一个UILabel,当用户按下按钮时,我希望标签为其值加一。但我对此有点麻烦。这是我的代码:

- (IBAction)addButton2:(id)sender {
    int integer = 1;
    integer++;
    [label1 setText:[NSString stringWithFormat:@"%i",integer]];
}

【问题讨论】:

  • 您编辑了您的问题,能否说明您所做的更改。以前的版本会崩溃

标签: objective-c ios cocoa-touch uilabel


【解决方案1】:

int 不响应 stringValue ...

原来的问题有 [int stringValue] 这不起作用

-(IBAction)addButton2:(id)sender {
    static int myInt = 1;
    myInt++;
    NSString *string = [NSString stringWithFormat:@"%d", myInt];
    [label setText:string];  
}

【讨论】:

    【解决方案2】:

    将静态添加到您的 int 中,那么整数只会被初始化一次。

    - (IBAction)addButton2:(id)sender 
    {
        static int integer = 1;
        integer++;
        [label1 setText:[NSString stringWithFormat:@"%d", integer]];
    }
    

    【讨论】:

    • @Man of One Way 嘿,当我这样做时,我必须按两次按钮才能真正开始计数。你知道它为什么这样做吗??
    • 首先值是什么,然后是1,然后又是1?
    • 好的,我明白了,我没有将整数设置为 1:D 哈哈,谢谢:D
    【解决方案3】:

    每次按下按钮时,您都将integer 重置为 1,然后将其增加一。 这将始终导致标签上显示2。 您需要将初始化移到此函数之外:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        integer = 1;
        [label1 setText:[integer stringValue]];
    }
    
    - (IBAction)addButton2:(id)sender
    {
        integer++;
        [label1 setText:[integer stringValue]];  
    }
    

    【讨论】:

    • 在 C 世界中,您总是将自动设为静态
    猜你喜欢
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多