Search code examples
cocoaswiftalignmentnstextfield

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

Solution

  • Try this:

    textLabel.alignment = .center

    I used this and it worked.