简体   繁体   English

将乘数添加到 Swift 中的 NSLayoutAnchor 约束

[英]Add multiplier to NSLayoutAnchor constraints in Swift

Anchor constraints simplify adding constraints but the multiplier property available in storyboard does not seem to be available for all types of constraints.锚约束简化了添加约束,但 storyboard 中可用的乘数属性似乎不适用于所有类型的约束。

For example, as per the answer here , you can center a label in a view with:例如,根据此处的答案,您可以将 label 在视图中居中:

view.addSubview(loadingLabel)
loadingLabel.translatesAutoresizingMaskIntoConstraints = false 
loadingLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
loadingLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

However, apparently, while you can set the multiplier for length constraints as in:但是,显然,虽然您可以设置长度约束的乘数,如下所示:

someView.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.4)

You cannot add a similar parameter to the CenterX or CenterY parameter, possibly because Apple doesn't think that makes sense for a point, although you can do this in Storyboard as discussed in this question .您不能将类似的参数添加到 CenterX 或 CenterY 参数,可能是因为 Apple 认为这对某个点没有意义,尽管您可以在 Storyboard 中执行此操作,如本问题中所述。

What is the best way to add a multiplier to the constraints for centering a point in order to make the point a proportion of the screen size from the top?将乘数添加到使点居中的约束以使该点与顶部的屏幕尺寸成比例的最佳方法是什么?

You can't add multipliers to the anchor methods for X and Y axis constraint, they are only available for the dimensional anchors.您不能将乘数添加到 X 和 Y 轴约束的锚定方法中,它们仅适用于尺寸锚定。 But, the NSLayoutContraint has an option for setting the multiplier.但是, NSLayoutContraint有一个设置乘数的选项。 So for example, if you want to set the label in the middle of the top and centre of the super view along the Y axis here's how you do this:因此,例如,如果您想将 label 设置在沿 Y 轴的超级视图的顶部和中心的中间,请执行以下操作:

view.addSubview(loadingLabel)
loadingLabel.translatesAutoresizingMaskIntoConstraints = false 
loadingLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
NSLayoutConstraint(item: loadingLabel, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 0.5, constant: 0).isActive = true

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM