Automatically expand UIView based on content?
I have a UIView A with backgrou开发者_如何学Gond color set and it contains a UIView B which height can change dynamically. When UIView B's height exceed UIView A, is it possible to have UIView A's height automatically match UIView B's?
I've tried using Autosizing, but it seems it is only meant to resize a child view relative to its parent, but not the other way around.
I also know that there is a method called sizeToFit
, but this needs to be called manually every time the content changes. Is there no other alternative?
While not fully automatic, you can use Key Value Observing to listen for changes to the content, and then do your UIView resizing in there. That prevents haven't to litter your code with code to resize the views everywhere that the content is changed.
For example (assuming you are doing this in a 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];
}
See the NSKeyValueObserving Protocol Reference for more information
Every time UIView B's height changes, try this:
if(CGRectGetHeight(B.frame)>CGRectGetHeight(A.frame)) {
A.frame = CGRectMake(CGRectGetX(A.frame),CGRectGetY(A.frame),CGRectGetWidth(A.frame),CGRectGetHeight(B.frame));
}
You also can use this code from my running application
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];
Hear scrollview is an scrollview object declared in .h
Hope it will help
精彩评论