问题描述
我目前正在设置具有以下结构的 UIScrollView
I'm currently setting up a UIScrollView with the following structure
UIScrollView --ContentView (UIView) --ContainerView1 (UIView) --UILabel1 --UILabel2 --ContainerView2 (UIView) --UILabel3 --UILabel4 --ContainerView3 (UIView) --UILabel5 --UILabel6
我已经为上面的所有元素固定了所有四个边,并且还定义了它们的高度限制(如果我没有这样做,故事板会抱怨零高度).
I've pinned all the four edges for all the elements above and also have defined their height constraints (Storyboard complaints of zero height if I didn't do so).
现在,每当我的 UILabel 从服务器接收到它的文本时,我都会为所有标签调用 sizeToFit.然后我使用 containerViews 的 lastObject 来计算假设的新高度.然后我调用 setNeedsLayout.但是,我的应用没有任何变化!
Now whenever my UILabel receives its text from the server, I call sizeToFit for all the labels. Then I use the lastObject of the containerViews to calculate the supposing new height. Then I call setNeedsLayout. However, nothing changes in my app!
这是我用来计算新高度和调整的代码.也许我编程错了?对不起,我的约束概念不强,可能也设置了错误的约束?
This is the code that I use to calculate the new height and adjust. Perhaps have I programmed it wrong? Sorry my concept on constraints is not strong, may have set the constraints the wrong way too?
- (void) relayoutAllSubViews: (NSArray *) arrayOfContainerViews { //Relayout subviews for (int i = 0; i < [arrayOfContainerViews count]; i++) { UIView * indView = [arrayOfContainerViews objectAtIndex:i]; if (indView.hidden == YES) { indView.frame = CGRectMake(indView.frame.origin.x, indView.frame.origin.y, indView.frame.size.width, 0); } else { UIView * lastSubviewInView = [indView.subviews lastObject]; CGFloat subviewEndPos = lastSubviewInView.frame.origin.y + lastSubviewInView.frame.size.height; if ((subviewEndPos - (indView.frame.origin.y + indView.frame.size.height)) > 0) { indView.frame = CGRectMake(indView.frame.origin.x, indView.frame.origin.y, indView.frame.size.width, (subviewEndPos - indView.frame.origin.y)); } } } //Adjust scrollview UIView * lastView = [self.scrollView.subviews lastObject]; CGFloat newEndPos = lastView.frame.origin.y + lastView.frame.size.height; self.contentView.bounds = CGRectMake(self.contentView.bounds.origin.x, self.contentView.bounds.origin.y, self.contentView.bounds.size.width, (newEndPos - self.contentView.bounds.origin.y)); self.scrollView.contentSize = self.contentView.bounds.size; [self.view setNeedsLayout]; }
需要帮助!!
推荐答案
//使用下面的代码来设置滚动视图的内容大小.
//use the below code to set the content size of a scroll view.
float newHeight=0.0f; for(UIView *subViews in [scrollViewObj subviews]) { if([subViews isKindOfClass:[UIView class]]) { newHeight=newHeight+(subViews.frame.origin.x+subViews.frame.size.height); } } NSLog(@"%f",newHeight); [scrollView setContentSize:CGSizeMake(300, newHeight)];//change the width as you need