2

I have a text label (NSTextField). I want it to pin to the upper left vertex of every object to show an element's number in UI. But my label shows only ZERO and doesn't move (it stays in the upper left corner). What I did wrong?

Here is my code in AppDelegate.swift:

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {


@IBOutlet weak var window: NSWindow!
@IBOutlet weak var drawingView: DrawingView!
@IBOutlet weak var label: NSTextField!


var localArray: [CGPoint] = []

func applicationDidFinishLaunching(aNotification: NSNotification) {

    label.textColor = NSColor(calibratedRed: 0.15, green: 0, blue: 0.75, alpha: 0.3)
    label.font! = NSFont(name: "Arial Bold", size: 60)!
    label.backgroundColor = NSColor.clearColor()
    label.stringValue = "\(localArray.count/4)"

    for (pointIndex, _) in localArray.enumerate() {

        let point = CGPoint(x: (localArray[(pointIndex/4)+1].x), y: (localArray[(pointIndex/4)+1].y))

        label.sizeToFit()
        label.frame = CGRect(origin: point, size: CGSize(width: label.bounds.width, height: label.bounds.height))
    }
}

And here is my code in DrawingView.swift:

   var delegate = NSApplication.sharedApplication().delegate as! AppDelegate
   delegate.localArray = myArray.map { return $0.coordSequence()[0] }

myArray contains cgpoints.

Am I right putting label parameters inside applicationDidFinishLaunching method?

1 Answers1

2

You are trying to update NSTextField probably from wrong thread.

dispatch_async(dispatch_get_main_queue(),{
     label.stringValue = "\((localArray.count/4)+1)"
})

Try to investigate you're array i could make assumption that when you set value of the label localArray.count is 0. Also keep in mind that you are working with Int and if localArray.count is 3 so 3/4 will be 0.

Oleg Gordiichuk
  • 15,240
  • 7
  • 60
  • 100
  • dispatch_async(dispatch_get_main_queue(),{ self.label.stringValue = "\(self.localArray.count/4)" }) –  Sep 05 '16 at 11:04
  • if I put **dispatch_async(dispatch_get_main_queue(), { self.label.stringValue = "\((self.localArray.count))" })**, result is the same. –  Sep 05 '16 at 11:23
  • could you simply print self.localArray.count and notice if it is more than 0 – Oleg Gordiichuk Sep 05 '16 at 11:23
  • I suppose text label not updating due to applicationDidFinishLaunching method. Seemingly, my label needs another method but I do not know what method are suitable for this situation. –  Sep 05 '16 at 11:24
  • Yes, I printed it. It's not 0. –  Sep 05 '16 at 11:25
  • In my case it's all right to get 0 for first four cgpoints. Then 1 for next four cgpoints. And so on. –  Sep 05 '16 at 11:29
  • 1
    try to use this http://stackoverflow.com/questions/20910467/changing-the-value-of-nstextfield-doesnt-update-label – Oleg Gordiichuk Sep 05 '16 at 11:30
  • Sorry Oleg Gordiichuk! Could you translate this code into Swift? I'm not good at Obj-C. –  Sep 05 '16 at 11:34