2012-08-28 30 views
1

我對Objective-C比較新,所以這可能非常簡單:我的應用程序中有一個文本框顯示彈藥計數,所以每次用戶點擊一個火按鈕,文本框中的數字將減少一(12> 11> 10等)爲0.我嘗試使用for和if語句,但它們不工作(我可能使用了不正確的語法) 。這是我使用的是什麼樣的權利,但很明顯,我需要的每個按鈕水龍頭減少一個文本框中的數字

- (IBAction)fire { 

    [ammoField setText:@"11"]; 

} 

- (IBAction)reload { 

    [ammoField setText: @"12"]; 

} 
+0

'int' count;在'.h'文件中,'viewDidLoad' count = something,do count - 在你的動作中,使用'stringWithFormat'來顯示字符串中的計數值。 – iNoob

回答

1

最簡單的方法是將文本轉換爲數字,遞減並重置文本,即用火法代替代碼:

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得到初始化。

+0

我試過了,它將整數降至-1,然後是-2等。下面是我在做的事情:在.h文件中:'code' NSInteger _ammoCount; 'code'在.m文件中:'code' - (IBAction)fire:(id)sender {_ammoCount--; [ammoDisplay setText:[NSString stringWithFormat:@「%d」,_ammoCount]]; }'代碼'爲了澄清,文本框最初是12,我希望它在第一次水龍頭時是11,然後是第二次時10,等等,然後停在0. –

+0

好吧,我已經更改了代碼,火災「按鈕被禁用,如果_ammoCount達到0. – Ander

+0

我試過了,它在第一次敲擊時變爲0。我將如何獲得它首先到11?設置_ammoCount等於12(我會在哪裏聲明)? –

-3

試試這個: -

int i; 
-(void)ViewDidLoad 
{ 

    i=12; 

} 
- (IBAction)fire 
{ 

    [ammoField setText:[NSString stringWithFormat:@"%d",i]]; 
    i--; 
} 

- (IBAction)reload { 
i = 12; 
[ammoField setText: [NSString stringWithFormat:@"%d", i]]; 
} 

希望它會爲你工作。它謝謝:)

0

集實例整數

int x; 

設定值

x = 12; 

做方法變更

- (IBAction)fire {  
[ammoField setText:[NSString stringWithFormat:@"%i",x]]; 
x--; 
} 
0

設定計數的在viewDidLoad中的值與一個int變量

火方法減少由1

計數和重新加載的方法來值返回到12個

日誌或使用相應值

相關問題