最簡單的方法是將文本轉換爲數字,遞減並重置文本,即用火法代替代碼:
NSInteger ammoCount = [ammoField.text integerValue];
ammoCount--;
ammoField.text = [NSString stringWithFormat:@"%d", ammoCount];
但是不要這樣做,它會讓寶寶史蒂夫喬布哭泣。
一個更好的辦法將是一個新的變量添加到類UIInteger
類型的跟蹤子彈的數量,即:
// in interface
NSInteger _ammoCount;
...
// in implementation
- (IBAction)fire {
_ammoCount--;
if (_ammoCount <= 0) {
_ammoCount = 0;
fireButton.enabled = NO;
}
[ammoField setText: [NSString stringWithFormat:@"%d", _ammoCount]];
}
- (IBAction)reload {
_ammoCount = 12;
[ammoField setText: [NSString stringWithFormat:@"%d", _ammoCount]];
fireButton.enabled = YES;
}
哦,不要忘記在某些時候調用reload
儘早確保_ammoCount和ammoField得到初始化。
'int' count;在'.h'文件中,'viewDidLoad' count = something,do count - 在你的動作中,使用'stringWithFormat'來顯示字符串中的計數值。 – iNoob