调用[super layoutSubviews]的正确方法是什么?

时间:2015-07-10 18:25:15

标签: ios objective-c facebook sdk

我刚刚在Facebook SDK for iOS中看到他们在最后而不是[super layoutSubviews];方法的开头调用了layoutSubviews

据我所知,我们应该始终把它作为第一行。 可以以不同的方式实现它会导致任何意外的UI行为吗?

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

3 个答案:

答案 0 :(得分:8)

根据UIView Class Reference

  

此方法的默认实现在iOS 5.1及更早版本中不执行任何操作。否则,默认实现使用您设置的任何约束来确定任何子视图的大小和位置。

因此,Facebook SDK示例应用程序在其实现结束时调用[super layoutSubviews]可能是最初为iOS 5.1之前的iOS版本构建的应用程序的工件。

对于iOS的更新版本,您应该在实施开始时调用layoutSubviews()。否则,超类会在您执行自定义布局后重新排列子视图,从而有效地忽略了ctype.h的实现。

答案 1 :(得分:4)

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.

答案 2 :(得分:2)

如果视图的内在内容大小发生变化,您最后必须最后调用[super layoutSubviews]。如果您更改按钮的标题,UIButton的内在内容大小将会更改,因此最后一次调用。

始终需要第一次调用[super layoutSubviews],因为iOS会根据约束更新布局。 但是,实施样本的技术最正确的方法应该是:

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