Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to call [super layoutSubviews]?

I just saw in the Facebook SDK for iOS that they call [super layoutSubviews]; at the end and not at the beginning of the layoutSubviews method.

As far as I know, we should always do it as the first line. Can implementing it a different way cause any unexpected UI behavior?

- (void)layoutSubviews
{
  CGSize size = self.bounds.size;
  CGSize longTitleSize = [self sizeThatFits:size title:[self _longLogInTitle]];
  NSString *title = (longTitleSize.width <= size.width ?
                     [self _longLogInTitle] :
                     [self _shortLogInTitle]);
  if (![title isEqualToString:[self titleForState:UIControlStateNormal]]) {
    [self setTitle:title forState:UIControlStateNormal];
  }

  [super layoutSubviews];
}
like image 463
ppalancica Avatar asked Jul 10 '15 18:07

ppalancica


People also ask

What is setNeedsLayout?

setNeedsLayout()Invalidates the current layout of the receiver and triggers a layout update during the next update cycle.

What is Layoutifneeded in Swift?

Lays out the subviews immediately, if layout updates are pending.


2 Answers

According to the UIView Class Reference,

The default implementation of this method does nothing on iOS 5.1 and earlier. Otherwise, the default implementation uses any constraints you have set to determine the size and position of any subviews.

Thus, that the Facebook SDK example app calls [super layoutSubviews] at the end of their implementation could be an artifact of the app being initially built for an iOS version prior to iOS 5.1.

For more recent versions of iOS, you should call [super layoutSubviews] at the beginning of your implementation. Otherwise, the superclass will rearrange your subviews after you do the custom layout, effectively ignoring your implementation of layoutSubviews().

like image 174
ndmeiri Avatar answered Oct 09 '22 10:10

ndmeiri


look into the code, before [super layoutSubviews], it is not about the frame. so put it at the end may work well too. I guess the coder must want to check the title and modify the title based on some rules, he thinks everytime the layoutSubviews being called is a right opportunity to do that, so he put the code here.

like image 30
childrenOurFuture Avatar answered Oct 09 '22 11:10

childrenOurFuture