2012-11-26 18 views
1

我正在製作一個iOS計算器,它對退格按鈕(用於刪除標籤上顯示的值的最後一個數字)有輕微的困難。製作一個計算器的退格按鈕

,以獲取標籤上的電流值我用

double currentValue = [screenLabel.text doubleValue] 

以下的其他問題,我想是這樣

-(IBAction)backspacePressed:(id)sender 
{ 
NSMutableString *string = (NSMutableString*)[screenLabel.text]; 

int length = [string length]; 

NSString *temp = [string substringToIndex:length-1] 
; 

[screenLabel.text setText:[NSString stringWithFormat:@"%@",temp]]; 

} 

但它不工作,

(Xcode中說「 setText已棄用「,」NSString可能不會響應setText「,並且標識符預計 IBAction內的第一行代碼)

我真的不明白這個代碼,使它自己的工作。

我該怎麼辦?

回答

3

應該

[screenLabel setText:[NSString stringWithFormat:@"%@",temp]]; 

您的Xcode清楚地說,你是想叫setText' method on an的NSString where as you should be calling that on a的UILabel . Your screenLabel.text is retuning an的NSString . You should just use screenLabel alone and should call上setText`。

只要使用,

NSString *string = [screenLabel text]; 

與問題是,你正在使用[screenLabel.text];這是不按Objective-C的語法正確調用text方法上screenLabel。要麼你應該使用,

NSString *string = [screenLabel text]; 

NSString *string = screenLabel.text; 

在這種方法中,我不認爲你需要使用NSMutableString。您可以改用NSString

總之你的方法可以寫成,

-(IBAction)backspacePressed:(id)sender 
{ 
    NSString *string = [screenLabel text]; 
    int length = [string length]; 
    NSString *temp = [string substringToIndex:length-1]; 
    [screenLabel setText:temp]; 
} 

按你的問題的意見,如果你想顯示爲零時,有沒有字符串存在(這是現已刪除),嘗試,

-(IBAction)backspacePressed:(id)sender 
{ 
    NSString *string = [screenLabel text]; 
    int length = [string length]; 
    NSString *temp = [string substringToIndex:length-1]; 

    if ([temp length] == 0) { 
    temp = @"0"; 
    } 
    [screenLabel setText:temp]; 
} 
+1

非常感謝! :) –

+1

或者跳過setText方法,只使用:「screenLabel.text = temp;」? – geowar