leifericf
leifericf

Reputation: 2372

How to centre-align NSTextField after setting its string value

There's probably a ridiculously simple solution to this (I'm almost embarrassed to ask).

Relevant code snippet from my view controller:

@IBOutlet weak var textLabel: NSTextField!

@IBAction func getTimeButton(sender: AnyObject) {
    let currentDate = NSDate()
    let dateFormatter = NSDateFormatter()
    dateFormatter.timeStyle = .ShortStyle
    textLabel.stringValue = dateFormatter.stringFromDate(currentDate)
}

Before pressing the "Get Time" button, the "Press Button" label is centred:

enter image description here

After pressing the button, the label gets left-alligned:

enter image description here

Label attributes:

enter image description here

I have set the labels constraints, but the constrains seem to get "reset" when the string value is set.

How can I make the label stay centred after setting the string value?

I've also tried to add this to my controller, but to no avail:

let textAlignment = NSTextAlignment.CenterTextAlignment
textLabel.alignment = textAlignment

Upvotes: 12

Views: 7010

Answers (1)

Akitoshi Asakura
Akitoshi Asakura

Reputation: 186

Try this:

textLabel.alignment = .center

I used this and it worked.

Upvotes: 17

Related Questions