【问题标题】:NSTextField setStringValue: append strings to NSTextFieldNSTextField setStringValue:将字符串附加到 NSTextField
【发布时间】:2012-04-10 23:34:18
【问题描述】:

我有大约 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 .

【问题讨论】:

    标签: objective-c macos cocoa nstextfield


    【解决方案1】:

    使用stringByAppendingString:stringWithFormat: 将两个字符串连接在一起:

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

    或:

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

    如果您真的想要一个基本的附加,请选择stringByAppendingString:,或者如果您需要空格/等,请选择stringWithFormat:

    【讨论】:

      【解决方案2】:

      怎么样:

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

      这里的想法是您获取 NSTextField 的原始内容并通过 stringWithFormat 组成一个新字符串,然后将该新字符串分配给您的 NSTextField。

      【讨论】:

        猜你喜欢
        • 2019-01-16
        • 2014-06-07
        • 2015-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多