简体   繁体   English

如何在 MacOS 上的 Swift 中使用自动布局以 x 轴为中心?

[英]How to center a view on the x axis using autolayout in Swift on MacOS?

Hi I'm just wanting to have a childView centered on the x axis of a NSViewController view using auto layout.嗨,我只是想有一个childView中心在x轴NSViewController view使用自动布局。 I'm doing the following:我正在做以下事情:

override func viewWillAppear()
{
    super.viewWillAppear()

    let childView = PagesView.init(frame: CGRect(x: 0, y: 0, width:100, height: 100))
    childView.translatesAutoresizingMaskIntoConstraints = false
    self.view.addSubview(childView)

    childView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
}

The childView doesn't even appear on the screen. childView甚至不会出现在屏幕上。 When I remove the last line, then it gets positioned at 0,0.当我删除最后一行时,它会被定位在 0,0。 So something about that last line is causing it go haywire and I'm not sure why?所以关于最后一行的某些事情导致它变得混乱,我不知道为什么? I've used this exact same logic on iOS and it has worked fine.我在 iOS 上使用了完全相同的逻辑,并且运行良好。

All views should have constraints to define its location and size.所有视图都应该有约束来定义其位置和大小。

// This would create dimension constraints if your class cannot already infer them
childView.widthAnchor.constraint(equalToConstant: 100).isActive = true
childView.heightAnchor.constraint(equalToConstant: 100).isActive = true

You also need to specify a vertical anchor constraint so the view has enough information to be displayed.您还需要指定一个垂直锚点约束,以便视图有足够的信息可以显示。

childView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将滚动视图与自动布局一起使用 Swift - Using Scroll View with Autolayout Swift 如何在Swift 3.0中以编程方式使用autolayout在UIView容器内水平居中2个或更多UIViews - How to center horizontally 2 or more UIViews inside a UIView container using autolayout programmatically in Swift 3.0 如何避免按钮从屏幕底部掉落并防止文本视图使用自动布局-xcode / swift消失? - How to avoid buttons dropping off bottom of screen and prevent text view from disappearing using autolayout - xcode/swift? 如何在Swift中自动布局按钮 - How to autolayout buttons in Swift 如何在 Swift for macOS 中创建带有左、中、右组件的“工具栏”? - How to create `Toolbar` with left, center, and right components in Swift for macOS? 如何将日期绘制为 X 轴 (Swift) - How to graph dates as X Axis (Swift) 如何在Swift 2中将Sprite随机放置在X轴上 - How to position a Sprite randomly on the X axis in Swift 2 以编程方式使用Autolayout Constraints将UIImageView置于UIView Swift 2.3 iOS10中 - Using Autolayout Constraints programmatically to center a UIImageView inside a UIView Swift 2.3 iOS10 如何将视图置于父视图的中心? swift - How can I center the view on the superview? swift 如何使用Swift 2.2使警报视图出现在视图控制器的中心 - How to make alert view appear in center of the view controller using swift 2.2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM