在Swift中向NSLayoutAnchor约束添加乘数 [英] Add multiplier to NSLayoutAnchor constraints in Swift

查看:122
本文介绍了在Swift中向NSLayoutAnchor约束添加乘数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

锚定约束简化了添加约束,但情节提要中可用的multiplier属性似乎不适用于所有类型的约束。

Anchor constraints simplify adding constraints but the multiplier property available in storyboard does not seem to be available for all types of constraints.

例如,如按照此处的答案,您可以在标签中将标签居中:

For example, as per the answer here, you can center a label in a view with:

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,乘数:0.4)

您不能向CenterX或CenterY参数添加类似的参数,可能是因为Apple认为尽管您可以在情节提要中进行此操作,但请按照以下说明进行操作:问题

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.

为使点居中以使点从顶部到屏幕的一部分成比例,向约束添加乘数的最佳方法是什么? / p>

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?

推荐答案

您无法将乘数添加到X和Y轴约束的锚点方法中,它们仅适用于尺寸锚点。但是, NSLayoutContraint 可以选择设置乘数。因此,例如,如果您想将标签设置在沿Y轴的超级视图的顶部和中心位置的中间,请按照以下步骤操作:

You can't add multipliers to the anchor methods for X and Y axis constraint, they are only available for the dimensional anchors. But, the NSLayoutContraint has an option for setting the multiplier. 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:

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

这篇关于在Swift中向NSLayoutAnchor约束添加乘数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆