2012-07-31 66 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; 
相關問題