【发布时间】:2016-09-27 20:16:06
【问题描述】:
我正在将一个 xib 视图添加到我的 ViewController 中。然后我将它的约束条件真正适合它
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
...
...
view!.addSubview(gamePreview)
gamePreview.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 9.0, *) {
// Pin the leading edge of myView to the margin's leading edge
gamePreview.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor).active = true
//Pin the trailing edge of myView to the margin's trailing edge
gamePreview.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor).active = true
} else {
// Fallback on earlier versions
view.addConstraint(NSLayoutConstraint(item: gamePreview, attribute: .TrailingMargin, relatedBy: .Equal, toItem: view, attribute: .TrailingMargin, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: gamePreview, attribute: .LeadingMargin, relatedBy: .Equal, toItem: view, attribute: .LeadingMargin, multiplier: 1, constant: 0))
}
view.addConstraint(NSLayoutConstraint(item: gamePreview, attribute: .Top, relatedBy: .Equal, toItem: self.topLayoutGuide, attribute: .Bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: gamePreview, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute,multiplier: 1, constant: 131))
}
我正在尝试做的事情:真正适合我的视图,将其限制在顶部、前导、尾随到 ViewController 的视图,并具有前缀高度。我添加到主视图的视图有自己的透明背景视图,所以不需要边距(视图是设备的宽度大小,所以)。
我在 if 中放置了两对应该相等的行(在我的尝试中),因为 if 中的前 2 行实际上仅在 iOS9 中可用>,而我正在尝试这样做else 语句中的相同内容,适用于所有设备(从 iOS 8 开始)。
这是我得到的:
左边是iOS9+,右边是iOS8+。透明背景被涂成红色以显示发生了什么(不要介意图像中的不同高度,它们在应用程序中是相同的高度,而不是查看左右添加的边距)
我也尝试了AutoLayoutDSL-Swift,但没有帮助,我不是这方面的专家,但每次尝试只会让事情变得更糟。
如何使用经典的 NSLayoutConstraints 方法编写这些约束,以及如何使用 AutoLayoutDSL 之类的框架或其分支以更好的方式编写所有这些约束? (或替代方案,尽管现在我主要关注官方库)
【问题讨论】:
-
在 iOS 9 之前的代码中,您使用了
leadingMargin和trailingMargin,因此您获得了利润。请改用leading和trailing -
另外,如果您进行了更改,那么相同的代码将适用于所有版本,iOS 8 及更高版本
-
有效!您还介意告诉我如何使用 AutoLayoutDSL-Swift 作为顶部锚点,特别是导航栏...我尝试了
view => gamePreview.top == view.top,以完成我进入倒数第二个约束的操作,但视图位于导航栏下方。 ..这将帮助我将所有这些臃肿的代码减少到由 4 分割的行中。我尝试将偏移量与self.navigationController!.navigationBar.height的总和相加,但它会产生编译错误,而它可以对实际数字进行数字化(如 30) . -
抱歉,不知道那是什么。我几乎只使用故事板
-
@Paulw11 我知道是对的,但是因为我知道如何让它在 iOS9 及更高版本中工作,我在问题中添加了该代码以帮助人们更容易地猜测我愿意做什么,并且确实有效。我想知道为什么我没有早点提出 view => gamePreview.trailing == view.trailing ... 我担心左右属性,它一直在失败
标签: ios iphone swift2 nslayoutconstraint