2012-03-27 82 views
3

我有10個按鈕,每個按鈕的名稱都不相同。在選擇每個按鈕時,我需要將按鈕的標題附加到NSTextField,而不刪除舊字符串。NSTextField setStringValue:將字符串附加到NSTextField

我嘗試過以下方法。

- (IBAction)nextButton:(NSButton*)sender 
{ 
    int tag = [sender tag]; 

    if (tag==1) { 

     [resultField setStringValue:[sender title]]; 
    } 
    else if (tag==2) { 

     [resultField setStringValue:[sender title]]; 
    } 
    else if (tag==3) { 

     [resultField setStringValue:[sender title]]; 
    } 
    else if (tag==4) { 
     [resultField setStringValue:[sender title]]; 
    } 
    else if (tag==5) { 
     [resultField setStringValue:[sender title]]; 
    } 
    else if (tag==6) { 

     [resultField setStringValue:[sender title]]; 
    } 
    else if (tag==7) { 

     [resultField setStringValue:[sender title]]; 
    } 
    else if (tag==8) { 

     [resultField setStringValue:[sender title]]; 
    } 
    else if (tag==9) { 

     [resultField setStringValue:[sender title]]; 
    } 
    else if (tag==10) { 

     [resultField setStringValue:[sender title]]; 
    } 
} 

這裏resultField是我的NSTextField。

setStringValue重寫新的字符串,這樣我couldnot能夠追加字符串NSTextField.Is有實現這個沒有簡單的方法或者使用的NSString值來保存以前的字符串,並與新的按鈕的字符串集合沿此字符串NSTextFiled值。

回答

6

如何像:

[resultField setStringValue: 
    [NSString stringWithFormat: @"%@ %@", [resultField stringValue], [sender title]]; 

這裏的想法是,你把你的NSTextField的原創內容,並通過stringWithFormat組成一個新的字符串,然後分配一個新的字符串到您的NSTextField。

3

使用stringByAppendingString:stringWithFormat:加入兩個字符串:

resultField.stringValue = [resultField.stringValue stringByAppendingString:sender.title]; 

或:

resultField.stringValue = [NSString stringWithFormat:@"%@ %@", resultField.stringValue, sender.title]; 

選擇stringByAppendingString:,如果你真的想要一個基本的追加,或stringWithFormat:如果你需要空白的/ etc之間。