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

拟墨画扇 提交于 2019-12-21 04:08:13

问题


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];
}

回答1:


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().




回答2:


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.




回答3:


You always have to call [super layoutSubviews] last, if the intrinsic content size of a view will be changed. If you change the title of the button, the intrinsic content size of the UIButton will be changed, therefore the last call.

The first call to [super layoutSubviews] is always required because iOS updates the layout based on the constraints. However, the technical most correct way of implementing your sample should be:

- (void)layoutSubviews
{
 [super 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];
}


来源:https://stackoverflow.com/questions/31347772/what-is-the-correct-way-to-call-super-layoutsubviews

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!