我正在玩一个原型,它将具有简单的可扩展形式,您可以在其中可编辑所有单元格的情况下即时添加/减去列。我正在将NSGridView作为解决方案,因为我需要所有单元格都易于编辑/选择,这使得NSTableView有点问题。
使用一些示例代码,我发现我已经能够创建一个使用NSTextField(labelWithString:String)(A)表现良好的版本,但是当我尝试使用NSTextField(string:String)时,它几乎无法正常工作同样,我只看到一栏,而不是3(B)。
如果我设置了列的宽度,那么我会看到全部三列,但是我失去了动态调整窗口大小并调整网格的功能-使用简单的标签(C)效果很好
这是我到目前为止的代码...代码中嵌入了所有选项(A),(B)和(C)。
import Cocoa
class ViewController: NSViewController {
// let myTextField = NSTextField(frame: NSMakeRect(20,20,200,40))
@IBOutlet weak var myGridViewContainer: NSView!
var gridView:NSGridView = NSGridView()
func embed(superview: NSView, subview: NSView, autoresizing: Bool = false) {
superview.addSubview(subview)
subview.translatesAutoresizingMaskIntoConstraints = autoresizing
superview.addConstraint(NSLayoutConstraint(item: superview, attribute: .top, relatedBy: .equal,
toItem: subview, attribute: .top, multiplier: 1, constant: 0))
superview.addConstraint(NSLayoutConstraint(item: superview, attribute: .bottom, relatedBy: .equal,
toItem: subview, attribute: .bottom, multiplier: 1, constant: 0))
superview.addConstraint(NSLayoutConstraint(item: superview, attribute: .leading, relatedBy: .equal,
toItem: subview, attribute: .leading, multiplier: 1, constant: 0))
superview.addConstraint(NSLayoutConstraint(item: superview, attribute: .trailing, relatedBy: .equal,
toItem: subview, attribute: .trailing, multiplier: 1, constant: 0))
}
override func viewDidLoad() {
super.viewDidLoad()
/* */
// (A) These labels work just fine...
let lb1 = NSTextField(labelWithString: "Label1")
let lb2 = NSTextField(labelWithString: "Label2")
let lb3 = NSTextField(labelWithString: "Label3")
let lb4 = NSTextField(labelWithString: "Label4")
let lb5 = NSTextField(labelWithString: "Label5")
let lb6 = NSTextField(labelWithString: "Label6")
/* */
/*
// (B) However, using these you'll only see the first column as the field spans the whole view
let lb1 = NSTextField(string: "Label1")
let lb2 = NSTextField(string: "Label2")
let lb3 = NSTextField(string: "Label3")
let lb4 = NSTextField(string: "Label4")
let lb5 = NSTextField(string: "Label5")
let lb6 = NSTextField(string: "Label6")
*/
gridView = NSGridView(views:
[
[lb1, lb3, lb5],
[lb2, lb4, lb6]
])
// gridView.frame = myGridViewContainer.frame
gridView.column(at: 1).xPlacement = .center
/*
// (C) Adding these lines will get all cols to show w/editable fields, however the resize no longer works
gridView.column(at: 0).width = 80.0
gridView.column(at: 1).width = 80.0
gridView.column(at: 2).width = 80.0
*/
embed(superview: myGridViewContainer, subview: gridView)
}
override func viewWillAppear() {
myGridViewContainer.wantsLayer = true
myGridViewContainer.layer?.backgroundColor = NSColor.red.cgColor
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
我可能只是选择移到tableView并放弃单元格的个别选择,因为我只真正需要它们是可编辑的,但在我放弃之前至少希望知道此解决方案是否可行。