如何在初始化时获取 NSView 的尺寸?
我有一个自定义视图(NSView
子类),我想在实例化视图时(即在 drawRect< 之前)根据视图的尺寸(宽度/高度)存储一些数据/code> 被调用。
我希望能够使用 initWithFrame
,并从传入的 NSRect
中获取边界,但是如果我检查调试器中的数据,我只会得到一个 < code>NSRect 实例,具有 (x=0, y=0), (width=0, height=0)
。大概还没有初始化?
更令人费解的是,如果我将帧宽度记录到控制台,我会得到该值两次:
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
CGFloat width = frame.size.width;
NSLog(@"width: %f", width);
}
}
此代码记录:
21/10/2011 09:40:55.733 Test App: width: 480.000000
21/10/2011 09:40:55.818 Test App: width: 0.000000
就好像 initWithFrame 在两个单独的线程中运行,并且我们有某种竞争条件。初始化视图时获取框架宽度的正确方法是什么?
更新[已解决]:此问题现已解决。事实证明,我在 Interface Builder 中有两个 NSView
子类的实例。一个被绘制为自定义视图
,另一个是侧面板中的对象
。我没有意识到向侧面板添加对象会导致它在运行时被实例化。删除了该对象,我的代码现在可以工作了。
I have a custom view (NSView
subclass), and I would like to store some data based on the dimensions (width/height) of the view when the view is instantiated, i.e. before drawRect
gets called.
I would expect to be able to use initWithFrame
, and take the bounds from the passed-in NSRect
, but if I examine the data in the debugger, I just get an NSRect
instance with (x=0, y=0), (width=0, height=0)
. Presumably it's not initialised yet?
More puzzling is that if I log the frame width to the console, I get the value twice:
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
CGFloat width = frame.size.width;
NSLog(@"width: %f", width);
}
}
This code logs:
21/10/2011 09:40:55.733 Test App: width: 480.000000
21/10/2011 09:40:55.818 Test App: width: 0.000000
It's as if initWithFrame is running in two separate threads and we have some kind of race condition. What's the correct way to get the frame width when the view is initialised?
UPDATE [SOLVED]: This issue has now been resolved. It turns out that I had two instances of my NSView
subclass in Interface Builder. One was drawn as a Custom View
and the other was an Object
in the side panel. I hadn't realised that adding an object to the side panel caused it to be instantiated at runtime. Removed the object and my code now works.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
initWithFrame 中传递的框架是视图使用的框架,您确定不是创建两个视图,或者调用了两次吗?
The frame passed in initWithFrame is the frame used by the view, are you sure you are not creating two views, or calling this twice?