[英]Automatically Grow a View's Height Based on It's Content
I have a (vertical) UIStackView
containing both a plain UIView
of height 50
(named sliderView
) and a UILabel
of height 36
defined in my storyboard. 我有一个(垂直)
UIStackView
包含一个高度为50
的普通UIView
(称为sliderView
),又包含一个在故事板中定义的高度为36
的UILabel
。 The label's alpha
property is initially set to 0.0
to make it invisible. 标签的
alpha
属性最初设置为0.0
,以使其不可见。
In the controller's viewDidLoad
I use UIViewController Containment to add another view controller's view to as a subview of sliderView
. 在控制器的
viewDidLoad
我使用UIViewController Containment将另一个视图控制器的视图添加为sliderView
的子视图。 This new subview does not necessarily match sliderViews
height. 此新子视图不一定与
sliderViews
高度匹配。 It might actually a fair bit taller. 实际上可能更高。
At first, this setup looks fine. 首先,此设置看起来不错。 Once I make the label visible, I see that it still starts at a y-position of
50
. 使标签可见后,我看到它仍然从
50
的y位置开始。 So, the sliderView
did not automatically stretch to use it's new child's height. 因此,
sliderView
不会自动拉伸以使用其新孩子的身高。 Makes sense. 说得通。
I thought that I could easily just call sizeToFit
on sliderView
to make those two heights fit. 我以为我可以轻松地在
sizeToFit
上调用sliderView
来使这两个高度合适。 Unfortunately, this does not seem to work. 不幸的是,这似乎不起作用。 Am I misunderstanding something here?
我在这里误会什么吗? Thanks!
谢谢!
Use following method to get the CGSize
required for NSString
text. 使用以下方法获取
NSString
文本所需的CGSize
。
- (CGSize)getHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font {
CGSize size = CGSizeZero;
if (text) {
CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName:font } context:nil];
size = CGSizeMake(frame.size.width, frame.size.height+20.0f);
}
return size;
}
Here width
parameter is the width of your label
and font
is the font specified for your label
. 在这里,
width
参数是label
的宽度,而font
是为label
指定的字体。 Call CGSize.height
to get the height. 调用
CGSize.height
获取高度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.