大家好,
谁知道如何定位NSButton在父视图下的另一个视图?
这是我写的代码,但是NSButton的位置不会改变,不管NSView在哪里。如果有人能调查一下并帮我解决这个问题,我将不胜感激。
@objc func printHello() {
var theButton = NSButton(frame: NSRect(x: 0, y: 0, width: 168, height: 32))
theButton.bezelStyle = .rounded
theButton.controlSize = .large
theButton.keyEquivalent = "r"
theButton.title = "Edit Chart Data"
self.superview?.addSubview(theButton, positioned: .below, relativeTo: self)
print(self.frame)
方法addSubview(theButton, positioned: .below, relativeTo: self)
没有定义项目的帧位置。定位:.below;部分实际上表示Z坐标
你所做的就是告诉视图在"self"下面添加一个子视图在它的等级制度中。这意味着如果self
和按钮的帧重叠,那么self
将在按钮的前面。使用.above
将把按钮放在前面。
您可以使用frame属性来实现您的目标或约束。如果是frame,则应该是
func placeView(_ targetView: NSView, belowView currentView: NSView) {
targetView.frame = NSRect(x: currentView.frame.minX,
y: currentView.frame.minY-currentView.frame.height,
width: currentView.frame.width,
height: currentView.frame.height)
}
使用方式:
self.superview?.addSubview({
let theButton = NSButton(frame: .zero)
placeView(theButton, belowView: self)
theButton.bezelStyle = .rounded
theButton.controlSize = .large
theButton.keyEquivalent = "r"
theButton.title = "New view"
return theButton
}())
当使用约束时,可以这样做:
func placeView(_ targetView: NSView, belowView currentView: NSView) {
let view = targetView.superview!
view.addConstraint(NSLayoutConstraint(item: currentView, attribute: .leading, relatedBy: .equal, toItem: targetView, attribute: .leading, multiplier: 1.0, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: currentView, attribute: .trailing, relatedBy: .equal, toItem: targetView, attribute: .trailing, multiplier: 1.0, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: currentView, attribute: .top, relatedBy: .equal, toItem: targetView, attribute: .bottom, multiplier: 1.0, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: currentView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: currentView.frame.height))
}
并像这样使用:
let theButton: NSButton = {
let theButton = NSButton(frame: NSRect(x: 0, y: 0, width: 0, height: 90.0))
theButton.translatesAutoresizingMaskIntoConstraints = false
theButton.bezelStyle = .rounded
theButton.controlSize = .large
theButton.keyEquivalent = "r"
theButton.title = "New view"
return theButton
}()
self.view.addSubview(theButton)
placeView(theButton, belowView: someView)
self.view.layoutSubtreeIfNeeded()