2012-07-31 81 views
0

我有一个名为containerView的UIView,其中有几个UILabel和UITextView,我调整containerView的最终高度,以后迭代其子视图的高度和总结它们。是否可以自动调整此高度?我调整使用像这样子视图的高度:创建基于UIView的子视图的自动调整大小的视图

CGFloat desiredHeight = [object.text sizeWithFont:[UIFont fontWithName:@"HelveticaNeue" size:15] constrainedToSize:CGSizeMake(self.imageView_.frameWidth , CGFLOAT_MAX) lineBreakMode:UILineBreakModeClip].height; 

也是它甚至可以调整特定子视图的Y原点要始终低于其他子视图?例如,在本containerView我有两个的UILabel,A和B.我想B到永远低于A.截至目前我在做什么是计算在layoutSubviews如下:

[B setFrameY:A.frameY + A.frameHeight]; 

是否有可能实现的东西像这样与自动调整大小的面具?我不能使用常量的原因是A的frameHeight是动态的,取决于文本的长度。

回答

0

我认为你的问题的简短答案是不,没有根据子视图自动调整视图的大小。根据你的后一个问题(根据另一个控件调整控件的框架),你应该查看来自WWDC 2012的各种“自动布局”视频。

当我最初回答这个问题时,我想我可能刚刚提供了解决方案,在重读您的问题时,我想您可能已经实施。我很抱歉。无论如何,我包括我的旧答案供您参考。

老答案:

关于第一个问题,不,我认为你必须通过你的子视图迭代来完成你想要的东西。我认为你不能用自动化的面具来做任何事情(那些设计是为了改变其他方式,根据他们的超级视角的变化调整子视图的框架)。虽然iOS 6承诺有一些增强功能,但我认为它不会解决您的具体挑战。尽管如此,你可以很容易地以编程方式做一些事情。你可以做类似如下:

- (void)resizeView:(UIView *)view 
{ 
    CGSize maxSize = CGSizeMake(0.0, 0.0); 
    CGPoint lowerRight; 

    // maybe you don't want to do anything if there are no subviews 

    if ([view.subviews count] == 0) 
     return; 

    // find the most lowerright corner that will encompass all of the subviews 

    for (UIView *subview in view.subviews) 
    { 
     // you might want to turn off autosizing on the subviews because they'll change their frames when you resize this at the end, 
     // which is probably incompatible with the superview resizing that we're trying to do. 

     subview.autoresizingMask = 0; 

     // if you have containers within containers, you might want to do this recursively. 
     // if not, just comment out the following line 

     [self resizeView:subview]; 

     // now let's see where the lower right corner of this subview is 

     lowerRight.x = subview.frame.origin.x + subview.frame.size.width; 
     lowerRight.y = subview.frame.origin.y + subview.frame.size.height; 

     // and adjust the maxsize accordingly, if we need to 

     if (lowerRight.x > maxSize.width) 
      maxSize.width = lowerRight.x; 
     if (lowerRight.y > maxSize.height) 
      maxSize.height = lowerRight.y; 
    } 

    // maybe you want to add a little margin?!? 

    maxSize.width += 10.0; 
    maxSize.height += 10.0; 

    // adjust the bounds of this view accordingly 

    CGRect bounds = view.bounds; 
    bounds.size = maxSize; 
    view.bounds = bounds; 
} 

只需调用任何“容器”视图中,您可能会(可能是最好的不正确的视图控制器遏制,这是一个不同的野兽混淆)想调整基于它是子视图。请注意,我只是调整大小(假设您不想移动子视图或视图的origin,如果您愿意,您可以轻松完成)。我也是递归地做这件事,但也许你不想。你的来电。

关于第二个问题,移动标签B到是一个标签下是很容易的:

CGRect frame = b.frame; 
frame.origin.y = a.frame.origin.y + a.frame.size.height; 
b.frame = frame; 
相关问题