How to find out the exact frame of a UIViewController view?

When can I find out the exact size of a view UIViewController?

Problem

I have a multi-line UILabelwhose frame depends on its text and the width of the parent view. Given that I need to position other views below UILabel , it is important that its frame completely covers the text space.

Currently, I am counting this size on viewDidLoad:

labelSize = [text sizeWithFont:font constrainedToSize:CGSizeMake(self.view.frame.size.width, MAX_HEIGHT)];

The problem is that the width of the parent view changes when UIViewControllerused as a modal form sheet or popover. If I use autoresizingMask, the UILabel frame is configured accordingly, but it is no longer suitable for text.

Where can I calculate the frame of this UILabel, knowing the exact size of the view UIViewController's?

Debugging efforts

This is the result of printing self.view.frame when displayed UIViewControlleras a modal form ( UIModalPresentationFormSheet).

viewDidLoad: (0.000000;0.000000;320.000000;480.000000)
viewWillAppear: (0.000000;0.000000;768.000000;960.000000)
afterDelay: (0.000000;0.000000;540.000000;576.000000)

Code that produces the above output:

- (void)viewDidLoad {
    [super viewDidLoad];
    [Utils logFrame:self.view.frame tag:@"viewDidLoad"];
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [Utils logFrame:self.view.frame tag:@"viewWillAppear"];
    [self performSelector:@selector(afterDelay) withObject:nil afterDelay:0.1];
}

- (void) afterDelay {
    [Utils logFrame:self.view.frame tag:@"afterDelay"];
}
+5
source share
4 answers

This is because your root view of the UIViewController uses autoresizingMask. I don’t think there is an “ideal time” to determine the size of your root UIViewController unless you override the root view method "layoutSubviews".

, , , , .

, , NSLog - .

+2

, viewWillAppear.

UIView layoutSubviews , . [self.view setNeedsLayout] , . , , .

+1

,

labelSize = [text sizeWithFont:font constrainedToSize:CGSizeMake(self.label.frame.size.width, MAX_HEIGHT)];

Instead of using view widths, use label widths at the size of the constraint. This should be available in the viewDidLoad, viewDidApper methods of the view controller.

0
source

try viewWillAppear. There is no reason not to know the size before the view is shown.

0
source

All Articles