开发者

How to add "1" to a UILabel in XCode

开发者 https://www.devze.com 2023-04-03 14:48 出处:网络
I need to add the value \"1\" onto whatever value开发者_JAVA技巧 is already in a UILabel view. For example, if the value of the UILabel were 2, I need to plus one to make it 3. How can I do this?

I need to add the value "1" onto whatever value开发者_JAVA技巧 is already in a UILabel view. For example, if the value of the UILabel were 2, I need to plus one to make it 3. How can I do this?

Thanks,

James


NSString has a handy method called intValue, which you can use like this:

label.text = [NSString stringWithFormat:@"%d",[label.text intValue]+1];

For your follow-up question, simply use an if statement:

if (label.tag == 1) {
    label.text = [NSString stringWithFormat:@"%d",[label.text intValue]+1];
} 

or maybe you mean

if (something) {
    label.tag = 1;
} 

label.text = [NSString stringWithFormat:@"%d",[label.text intValue]+label.tag];


In Swift 2.0 I used:

let currentLabelNumber: Int? = Int(label.text!)! + 1
      label.text = "\(currentlabelNumber!)"

I tried putting

let currentLabelNumber: Int? = Int(label.text!)! + 1

at the top of the function and reusing it but it didn't like that. Had to use both lines each time I wanted to increase the label value.

Hope this helps someone!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号