Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why isn't -layoutSubviews being called?

I'm trying to create a custom layout for some subviews. My file is a ViewController, so I have to refer to its view as self.view. The subviews are subviews of self.view.

When I call [self layoutSubviews]; explicitly in viewDidLoad, it will execute the code in -layoutSubviews without a problem.

However, I've read that I shouldn't call -layoutSubviews explicitly, or call it on self since that's a UIViewController. I tried implementing -setNeedsLayout by calling it like this: [self.view setNeedsLayout] in viewDidLoad, and taking out the explicit call of -layoutSubviews but keeping its declaration. But that didn't seem to work.

I was linked to an article about when layoutSubviews is called and it seems like it should be called when I add subviews, but that doesn't seem to be happening here.

If I want to be safe, and do things the way it suggests in the class reference for UIView and its methods, how should I go about being able to use both methods?

like image 389
alsuhr Avatar asked Nov 23 '25 10:11

alsuhr


2 Answers

There is no such thing as -[UIViewController layoutSubviews] or -[UIViewController setNeedsLayout]. These are UIView methods.

If you want to use the layoutSubviews system, you need to subclass your top-level UIView and implement it there. By default, it does nothing. If you want to layout your views using the view controller, then I would name the methods something else (like layout, since a view controller doesn't have "subviews") to avoid confusion with UIView.

like image 115
Rob Napier Avatar answered Nov 25 '25 23:11

Rob Napier


You should never call -layoutSubviews directly. It might be detrimental to performance, but other reasons might as well apply. Instead call -setNeedsLayout. This method sets a flag (or Boolean) that on some next drawing pass the -layoutSubviews method should be called (several methods might set this flag, but it won't force a redraw until the time is right).

Does your -layoutSubviews implementation call -layoutSubviews on the super class?

Perhaps you should show some code so we might help you further with this issue.

like image 32
Wolfgang Schreurs Avatar answered Nov 26 '25 00:11

Wolfgang Schreurs



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!