2011-07-20 103 views
3

我有背景色設置一個UIView A和它包含一個UIView B,其高度可以動態地改變。當UIView B的高度超過UIView A時,是否有可能讓UIView A的高度自動匹配UIView B?根據內容自動展開UIView?

我一直在使用自動調整大小嚐試過,但現在看來,這只是爲了子視圖相對於其父一個調整,而不是周圍的其他方式。

我也知道,有一個名爲sizeToFit方法,但這需要每次內容更改爲手動調用。有沒有其他的選擇?

回答

2

雖然不是全自動的,你可以使用Key Value Observing偵聽改動的內容,然後做你的UIView在那裏調整。這樣可以防止不必讓代碼隨代碼一起在內容發生更改的任何地方調整視圖大小。

例如(假設你是在一個UIViewController這樣做):

// Somewhere when the view is loaded, probably in -(void)viewDidLoad do this: 
[self addObserver:self forKeyPath:@"viewA.frame" options:0 context:NULL]; 

// Then, implement this method 
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { 
    // Resize your views, either using sizeToFit, Purple Ninja's method, or another method 
} 

// Finally, make sure to unregister in dealloc: 
- (void)dealloc { 
    [self removeObserver:self forKeyPath:@"viewA.frame"]; 
    // ... 
    [super dealloc]; 
} 

更多信息,請參見NSKeyValueObserving Protocol Reference

+0

+1還在研究是否有其他方法。 – pixelfreak

+0

很好的答案,它幫助了我。只是注意,使用sizeToFit,如建議在observeValueForKeyPath評論:......你需要重寫sizeToFit擺在首位,如果您使用的UIView的子類。 +1 – katzenhut

1

每次UIView的B的高度變化,試試這個:

if(CGRectGetHeight(B.frame)>CGRectGetHeight(A.frame)) { 
    A.frame = CGRectMake(CGRectGetX(A.frame),CGRectGetY(A.frame),CGRectGetWidth(A.frame),CGRectGetHeight(B.frame)); 
} 
+0

感謝@Purple。我知道如何手動調整A的大小。我想知道是否有辦法*不*必須這樣做。 – pixelfreak

0

您也可以使用此代碼從我運行的應用程序

CGRect frame=CGRectMake(0, 0,, 405); 
     frame.origin.x=self.ScrollView.frame.size.width *i; 
     frame.origin.y=0; 


     frame.size=self.ScrollView.frame.size; 
     UIImageView *subimg=[[UIImageView alloc]initWithFrame:frame]; 
     imageView.userInteractionEnabled = YES; 
     imageView.autoresizingMask = (UIViewAutoresizingFlexibleWidth); 
     subimg.image=[array objectAtIndex:i]; 
     [self.ScrollView addSubview:subimg]; 
     [subimg release]; 

     self.ScrollView.contentSize=CGSizeMake(self.ScrollView.frame.size.width*array.count, self.ScrollView.frame.size.height); 
      [self.view addSubview:imageView]; 

聽滾動視圖的一個滾動視圖對象中.H

聲明

希望這將有助於