swift2 如何以编程方式创建多个NSTextField?

fdbelqdn  于 2022-11-06  发布在  Swift
关注(0)|答案(2)|浏览(174)

我有一个CGPoints数组。我需要为数组中的每四个点创建一个个人标签,所以我需要以编程方式创建几个NSTextField。我可以通过单击鼠标来添加点,并且可以创建任意多个点。这些点的标签必须都是活动的,以便同时为用户显示文本。我该如何做呢?
(macOS、Xcode 7、Swift 2)
下面是我的代码:

import Cocoa
@NSApplicationMain

class AppDelegate: NSObject, NSApplicationDelegate {
    @IBOutlet weak var window: NSWindow!
    @IBOutlet weak var drawView: DrawView!
    @IBOutlet weak var view: NSView!
    let label = NSTextField(frame: NSMakeRect(0,0,100,50))
    var pointsArray: [CGPoint] = []

    func applicationWillUpdate(aNotification: NSNotification) {
        label.backgroundColor = NSColor.clearColor()
        label.bezeled = false
        label.stringValue = "\(pointsArray.count/4)"

        var multiple = (1...25).map { _ in label }

        for index in 0..<(pointsArray.count/4) {

            let point = CGPoint(x: pointsArray[index*4].x, y: pointsArray[index*4].y)
            label.frame = CGRect(origin: point, size: CGSize(width: label.bounds.width, height: label.bounds.height))

            let sticker = multiple[index]
            view.addSubview(sticker)
        }
    }
}

在运行时,我只看到一个标签,但我需要同时看到几个标签(在每四个CGPoint上)。如果我有100个CGPoint,我必须有25个标签。

q9yhzks0

q9yhzks01#

我只看到一个标签
现在我已经理顺了大括号和缩进,很容易看出原因。您的循环构造不正确,因此您创建了一个标签,并更改了它的框架四次。您需要创建四个具有四个独立框架的独立标签。

ztmd8pv5

ztmd8pv52#

用于创建多个NSTextField的代码:

import Cocoa
@NSApplicationMain

class AppDelegate: NSObject, NSApplicationDelegate {
    @IBOutlet weak var window: NSWindow!
    @IBOutlet weak var drawView: DrawView!
    var view = NSView(frame: NSMakeRect(0,0,1920,1080))
    var pointsArray: [CGPoint] = []

    var label1 = NSTextField(frame: NSMakeRect(0,0,100,50))
    var label2 = NSTextField(frame: NSMakeRect(0,0,100,50))
    var label3 = NSTextField(frame: NSMakeRect(0,0,100,50))
    .............
    .............
    var label25 = NSTextField(frame: NSMakeRect(0,0,100,50))

    func applicationWillUpdate(aNotification: NSNotification) {

        var labelArray = [label1, label2, label3, ..... label25]

        for i in 0..<(pointsArray.count/4) {

            labelArray[i].backgroundColor = NSColor.clearColor()
            labelArray[i].bezeled = false
            labelArray[i].stringValue = "\(i+1)"

            let point = CGPoint(x:(pointsArray[i * 4].x), y:(pointsArray[i * 4].y))

            var originPoint: [CGPoint] = []
            originPoint.append(point)

            labelArray[i].frame = CGRect(origin: originPoint[0], 
                size: CGSize(width: labelArray[i].bounds.width, height: labelArray[i].bounds.height))

            view.addSubview(labelArray[i])
        }
    }

相关问题