NSTextField setStringValue:将字符串附加到NSTextField

3

我有10个不同名称的按钮。选择每个按钮时,我需要将按钮的标题附加到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覆盖了新字符串,因此我无法将字符串附加到NSTextField中。是否有更简单的方法来实现这一点,或者使用NSString值来保存先前的字符串,并将该字符串与新按钮的字符串值一起设置到NSTextFiled中。

2个回答

6
如何尝试这样的方法:
[resultField setStringValue: 
    [NSString stringWithFormat: @"%@ %@", [resultField stringValue], [sender title]];

这里的想法是你通过stringWithFormat构建一个新字符串,然后将其赋值给你的NSTextField,以替换原始内容。

3
使用stringByAppendingString:或者stringWithFormat:来连接两个字符串:
resultField.stringValue = [resultField.stringValue stringByAppendingString:sender.title];

或者:

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

如果你只想简单的追加字符串,请选择stringByAppendingString:,如果你需要字符串之间有空格等其他内容,请选择stringWithFormat:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接