简体   繁体   中英

Resize UIView to fit its content

The problem is, that I do have a view containing 3 parts.

The first part is a simple header - same height always! The second part is a simple description line - same height always!

Now the problem is the third part. It's a viewContainer for dynamically calculated subviews (each of them having a custom controller). The height of the content is dynamic caused by some text information downloaded from a backend. So some times I would need to scroll to be able to read the whole text, sometimes not.

Currently I am doing it this way:

  • Calculate the size of the UILabel for a specific text.
  • Then resize the parent view so fit the UILabel (if smaller).
  • Then resize the scrollView of my 3-Part-ViewController-View to fit its subviews.

The detail viewController with the dynamic content:

    self.labelDescription.text = self.customData.descriptionText;
    [self.labelDescription sizeToFit];
    if(self.view.frame.size.height < (self.labelDescription.frame.size.height + self.labelDescription.frame.origin.y)) {
    CGRect newSize = CGRectMake(0,
                                0,
                                self.view.frame.size.width,
                                self.labelDescription.frame.size.height +
                                self.labelDescription.frame.origin.y);
    self.view.frame = newSize;
    }

The resizing of the scroll view after adding and resizing my detail view:

[self addChildViewController:controllerCustomData];
[self.scrollView addSubview:controllerCustomData.view];    
CGRect newRect = CGRectMake(0,
                            self.viewElementDetailContentContainer.frame.origin.y,
                            controllerCustomData.view.frame.size.width,
                            controllerCustomData.view.frame.size.height);
controllerCustomData.view.frame = newRect;
self.scrollView.contentSize = CGSizeMake(self.scrollView.contentSize.width, newRect.origin.y + newRect.size.height);

So my question is, are there easier ways to do this?

You could create a method that does everything you need. You'll need to write the method (maybe methodS) once and use it passing the necessary arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM