我有一个文本标签(NSTextField)。我希望它固定到每个对象的左上角,以在 UI 中显示元素的编号。 但我的标签只显示零并且没有移动(它停留在左上角)。我做错了什么?
这是我在 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 方法中是否正确?
最佳答案
您可能正在尝试从错误的线程更新 NSTextField。
dispatch_async(dispatch_get_main_queue(),{
label.stringValue = "\((localArray.count/4)+1)"
})
尝试调查您的数组,我可以假设当您设置标签 localArray.count
的值时为 0。另请记住,您正在使用 Int
并且如果 localArray.count
是 3,那么 3/4 将是 0。
关于Swift:文本标签未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39328946/