Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically expand UIView based on content?

I have a UIView A with background 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?

like image 602
pixelfreak Avatar asked Dec 12 '25 10:12

pixelfreak


2 Answers

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

like image 94
Darren Clark Avatar answered Dec 14 '25 02:12

Darren Clark


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));
}
like image 41
Purple Ninja Avatar answered Dec 14 '25 04:12

Purple Ninja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!