Swift:文本标签未更新

时间:2016-09-05 10:46:36

标签: swift macos label appdelegate

我有一个文本标签(NSTextField)。我希望它固定到每个对象的左上角,以在UI中显示元素的数字。 但我的标签只显示ZERO并且不移动(它停留在左上角)。我做错了什么?

这是我在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))
    }
}

这是我在DrawingView.swift中的代码:

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

myArray包含cgpoints。

我是否正确将标签参数放在 applicationDidFinishLaunching 方法中?

1 个答案:

答案 0 :(得分:2)

您正在尝试从错误的线程更新NSTextField。

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

尝试调查您的数组我可以假设当您设置标签localArray.count的值为0.时还请记住,您正在使用Int和{{1} }是3所以3/4将是0。

相关问题