swift2nsviewnstextfieldaddsubviewcgpoint

How to programmatically create several NSTextFields?


I have an array of CGPoints. I need a personal label for every fourth point in array, so I need to create several NSTextFields programmatically. I can add points with mouse clicks and can create as many points as I wish. Labels for these points must be all active to show text for user simultaneously. How can I do it?

(macOS, Xcode 7, Swift 2)

Here's my code:

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)
        }
    }
}

At runtime I see only one label but I need to see several labels simultaneously (on every fourth CGPoint). If I have 100 CGPoints I must have 25 labels.


Solution

  • I see only one label

    Now that I've straightened out your curly braces and indentation, it's easy to see why. Your loop is incorrectly constructed, so that you create one label and change its frame four times. You need to create four separate labels with four separate frames.