我有一系列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个CGPoints,我必须有25个标签。
答案 0 :(得分:2)
我只看到一个标签
现在我已经理顺了你的花括号和缩进,很容易理解为什么。您的循环构造不正确,因此您可以创建一个标签并将其框架更改四次。您需要使用四个单独的框架创建四个单独的标签。
答案 1 :(得分:0)
创建多个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])
}
}