【问题标题】:Why UIView calls getter method of frame on setting its frame?为什么 UIView 在设置它的框架时调用框架的 getter 方法?
【发布时间】:2023-04-08 18:24:01
【问题描述】:

UIView 在设置框架时调用框架的 getter 方法。

下面是测试代码:

@interface Test: UIView

@end

@implementation Test

-(void) setFrame:(CGRect) frame {
    super.frame = frame;
    NSLog(@"Frame set!!!");
}

-(CGRect) frame {
    NSLog(@"Frame!!!");
    return super.frame;
}

@end

Test* inst = [[Test alloc] init];
inst.frame = CGRectMake(0, 0, 123, 123);

我发现它会在调用setFrame:时调用frame。 我很想知道那里发生了什么?有人知道吗?

仅供参考,输出是:

Frame!!!
Frame set!!! // Due to the call of initWithFrame:
Frame!!!
Frame set!!! // Setter

【问题讨论】:

  • 询问苹果。他们编写了代码。

标签: ios objective-c uiview frame


【解决方案1】:

代码下面的第一件事,

Test* inst = [[Test alloc] init];
inst.frame = CGRectMake(0, 0, 123, 123);

应该给出类似的输出,

Frame!!!
Frame set!!!
Frame!!!
Frame set!!!

我的意思是两次,因为第一次是你 allocinit 它,第二次是你设置框架时。

现在进入重点,

实际上并不是先调用frame,肯定是先调用setFrame,而是在setFrame方法中,

   super.frame = frame;

调用frame 方法,让你的输出看起来像!!

如果您将在setFrame 方法中评论super.frame = frame;,那么我认为您的frame 方法将不会被调用!

你应该把breakpoint放在这两个方法中然后测试!

更新:

试试下面的代码,

 -(void) setFrame:(CGRect) frame {

super.frame = frame;
NSLog(@"Frame set!!!");
}

-(CGRect) frame1 {

NSLog(@"Frame!!!");
return super.frame;
}

-(void) setFrame:(CGRect) frame1 {

super.frame = frame1;
NSLog(@"Frame set!!!");
}

-(CGRect) frame1 {

NSLog(@"Frame!!!");
return super.frame;
}

现在它不会调用frame1 方法。您已将方法名称指定为frame,这意味着您是overriding 超类的frame method,因此如果您调用super.frame = frame;,那么它肯定会调用frame 方法(如果overridden 它将被调用)。

【讨论】:

  • 是的,因为initWithFrame:的调用,它们会输出两次。我已经在帖子中更正了。
  • 在方法和检查中放置断点。然后评论super.frame = frame;然后检查!
  • 重点是我还在纠结的事情!!!我不明白为什么 UIView 的 setFrame 方法必须调用 frame 方法。这是不安全的,因为人们可以覆盖 frame 方法来做一些影响布局的讨厌的事情。我个人认为不应参与framemethod 的调用。
  • 因为你覆盖了超类的frame 方法。将该方法更改为frame1,那么它将不会被调用。我正在用代码 sn-p 更新我的答案以了解!
  • ? 可能我的表达有问题。我决定继承 UIView 并重写 frame&setFrame 方法只是为了检测这两个方法的调用状态。我正在探索为什么 UIView 在 UIView 的 setFrame 上调用 UIViewframe。这才是真正让我困惑的地方。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-18
  • 2015-11-18
  • 1970-01-01
  • 2017-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多