iOS如何根据UILabel在其中制作UIView的动态宽度/自动布局 [英] iOS how to make dynamic width / autolayout of UIView according to UILabel within it

查看:569
本文介绍了iOS如何根据UILabel在其中制作UIView的动态宽度/自动布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力解决一些菜鸟问题。我有一个 UIView ,其中我显示了一些价格。我希望 UIView 根据价格具有动态宽度,如果是1欧元,那么它将是例如 20pt ,如果是2300欧元,那么它的宽度将是 50pt

I am struggling with maybe a bit of a rookie issue. I have a UIView within which I display some price. I want the UIView to be of a dynamic width according to the price, if its 1 Euro, then it will be e.g. 20pt, if its 2300 Euro, then it will be like 50pt in width.

我试图使用故事板的约束但没有运气。是否可以在故​​事板中进行,或者我必须计算 UILabel 的宽度,然后设置 UIView 以编程方式?

I was trying to use the storyboard's constraints but without luck. Is it possible to do it within storyboard or do I have to calculate the width of UILabel and then set the width of UIView programmatically?

提前谢谢。

推荐答案

是的,你可以在故事板中做到这一点。在视图中添加标签并将其固定到左右边缘(如果需要,也可以将其固定在顶部和底部)。在x和y方向上为其超视图提供视图约束,但不要给它一个宽度约束(如果没有将标签的顶部和底部固定到它,则需要高度约束)。然后视图应根据其内容随标签一起展开。

Yes, you can do this in the storyboard. Add a label to your view and pin it to the left and right edge (top and bottom if you want also). Give the view constraints to its superview in the x and y directions, but do not give it a width constraint (it will need a height constraint if you didn't pin the top and bottom of the label to it). The view should then expand with the label depending on its content.

这篇关于iOS如何根据UILabel在其中制作UIView的动态宽度/自动布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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