150

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

rptwsthi
  • 10,094
  • 10
  • 68
  • 109
Alexsander Akers
  • 15,967
  • 12
  • 58
  • 83
  • Is your NSTextField referenced as an IBOutlet and attached properly (if you're using Interface Builder that is...) – jlindenbaum May 15 '10 at 20:15

7 Answers7

240

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.)

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
Ken Aspeslagh
  • 11,484
  • 2
  • 36
  • 42
  • 28
    The way to do this in Swift is just `stringValue`, then you can set it to whatever string you want. –  Oct 06 '15 at 23:36
49

Just do something like this:

myLabel.stringValue = @"My Cool Text";
Richard de Wit
  • 7,102
  • 7
  • 44
  • 54
Jim
  • 499
  • 4
  • 2
20

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

pkamb
  • 33,281
  • 23
  • 160
  • 191
Alexander
  • 9,737
  • 4
  • 53
  • 59
  • This is a good answer for the most recent dev environment. Btw why is this not part of the NSTextField documentation? I went there first and thought it would be really obvious to find how to do this, but it was not there... EDIT: I found it, it is just not in the obvious place of "Topics", because stringValue is actually a property of parent class NSControl, and appears in "Overview" – wllychng Jun 16 '18 at 17:38
10

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.

Maulik Rajani
  • 639
  • 8
  • 17
2

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.

Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
0

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"]]];
Alp Altunel
  • 3,324
  • 1
  • 26
  • 27
-3

just do this

[textField setString:@"random"];
Joe Manto
  • 9
  • 7
  • 2
    wrong. This is how you set up a `UITextField`. The question is about Cocoa NSTextField that is a different animal. – Duck Jul 08 '17 at 14:52