145
votes

I'm trying to set the text in an NSTextField, but the -setStringValue: and -setTitleWithMnemonic: methods are not working. Any ideas?

7
Is your NSTextField referenced as an IBOutlet and attached properly (if you're using Interface Builder that is...)jlindenbaum

7 Answers

238
votes

setStringValue: is the way to do it. You should make sure your outlet is being set properly. (In the debugger, make sure your textfield variable is not null.)

48
votes

Just do something like this:

myLabel.stringValue = @"My Cool Text";
17
votes

Just myLabel.stringValue = "MY TEXT" works here, using Swift and Xcode 6.

9
votes

Swift 4

self.yourTextField.stringValue = "Your_Value"

Note: Fetching value from self.yourTextField.stringValue at that will get warning message i.e. Warning Message To avoid this kind of warning you can use like this (suggested way)

DispatchQueue.main.async {
 your code ... 
} 

OR also refer to this.

1
votes

If the value you're trying to set happens to be an integer rather than a string, you don't need to convert the integer value to a string manually; you can just call:

myLabel.integerValue = i;

The integerValue property is defined on NSTextField's parent class, NSControl. See that linked documentation page for a full list of methods it supports.

0
votes

ObjectiveC:

[label setStringValue: @"I am a label"];

original code I use in my code to display application version is:

    [lblVersion setStringValue:[NSString stringWithFormat:@"v%@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]]];
-3
votes

just do this

[textField setString:@"random"];