【发布时间】:2019-04-04 15:14:15
【问题描述】:
我正在玩弄约束,试图了解它们是如何工作的,并尝试学习如何在没有 IB 的情况下构建 UI,但我没有得到预期的结果。在下面的代码中,如果我在最后注释掉约束,我可以看到紫色视图。如果我取消注释它们,我得到的只是一个空窗口,我希望视图被固定在主视图的左侧、右上角。
我也尝试使用 centerX 和 centerY 属性做类似的事情,尝试将视图居中在窗口中间,当它们被激活时,我再次得到一个空窗口。
任何帮助表示赞赏!
import Cocoa
class ViewController : NSViewController {
override func loadView() {
// NSMakeRect parameters do nothing?
let view = NSView(frame: NSMakeRect(0,0,400,2000))
view.wantsLayer = true
view.layer?.borderWidth = 5
view.layer?.borderColor = NSColor.gray.cgColor
self.view = view
}
override func viewWillAppear() {
super.viewWillAppear()
// Do any additional setup after loading the view.
createMasterView()
}
func makeView() -> NSView {
let view = NSView()
view.translatesAutoresizingMaskIntoConstraints = false
view.setFrameSize(NSSize(width: 600, height: 100))
view.wantsLayer = true
view.heightAnchor.constraint(equalToConstant: 1000)
return view
}
func createMasterView() {
let mainView = self.view
let headerView = makeView()
headerView.layer?.backgroundColor = NSColor.purple.cgColor
headerView.layer?.borderWidth = 5
headerView.layer?.borderColor = CGColor.black
mainView.translatesAutoresizingMaskIntoConstraints = false
mainView.addSubview(headerView)
headerView.topAnchor.constraint(equalTo: mainView.topAnchor).isActive = true
headerView.leadingAnchor.constraint(equalTo: mainView.leadingAnchor).isActive = true
headerView.trailingAnchor.constraint(equalTo: mainView.trailingAnchor).isActive = true
}
}
编辑:我还在下面包含了我的 AppDelegate 代码。我对这一切还是很陌生,所以代码是我从各种教程中拼凑起来的东西。
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
var windowController: NSWindowController!
var window: NSWindow!
var windowTitle = "Test App"
var customBGColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)
func applicationDidFinishLaunching(_ aNotification: Notification) {
createMainWindow()
}
func createMainWindow() {
window = NSWindow()
// window.alphaValue = 0.5
window.backgroundColor = customBGColor
window.title = windowTitle
window.styleMask = NSWindow.StyleMask(rawValue: 0xf)
window.backingType = .buffered
window.contentViewController = ViewController()
window.setFrame(NSRect(x: 700, y: 200, width: 1920, height: 1080), display: false)
windowController = NSWindowController()
windowController.contentViewController = window.contentViewController
windowController.window = window
windowController.showWindow(self)
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
【问题讨论】: