如何解决如何将 NSView 定位在另一个 NSView 下方?
美好的一天,
谁知道如何将 NSButton 放置在其父视图中的另一个视图下方?
这是我写的代码,但无论 NSView 在哪里,NSButton 的位置都不会改变。如果有人能够调查并帮助我解决问题,我将不胜感激。
@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)
方法没有定义项目的框架位置。 “定位:.下方”部分实际上是指 Z 坐标。
所以你所做的就是告诉视图在其层次结构中的“self”下面添加一个子视图。这意味着如果 self
的帧与按钮重叠,那么 self
将位于按钮的前面。使用 .above
会将按钮放在前面。
您可以使用任一框架属性来实现您的目标或约束。使用框架应该是这样的
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,multiplier: 1.0,constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: currentView,attribute: .trailing,attribute: .top,attribute: .bottom,attribute: .height,toItem: nil,attribute: .notAnAttribute,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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。