简体   繁体   English

具有自定义视图的Xcode自动布局

[英]Xcode Auto Layout with custom view

I am working on my first project using Auto Layout and custom views. 我正在使用自动版式和自定义视图进行第一个项目。 My question is this: 我的问题是这样的:

I created my custom view in Interface Builder then added constraints to stretch the view if needed which is working the way I want it to, however, consider the following code snippet from my custom view class - 我在Interface Builder中创建了自定义视图,然后根据需要添加了约束以拉伸视图,这符合我的期望,但是,请考虑以下来自我的自定义视图类的代码片段-

// MyCustomView // MyCustomView

-(id)initWithCoder:(NSCoder*)decoder
{
    self = [super initWithCoder:decoder];
    if(self != nil)
    {
        CGFloat layerWidth = self.bounds.size.width;
                CGFloat layerHeight = self.bounds.size.height;
    }
    return self;
}

This code return the size set in IB. 此代码返回在IB中设置的大小。 My drawing code relies on the new width and height (if the view has been stretched) but I don't know how to retrieve them. 我的绘图代码依赖于新的宽度和高度(如果视图已拉伸),但是我不知道如何检索它们。

First, that code is utterly silly because you are creating variables layerWidth and layerHeight and throwing them away, which is pointless. 首先,该代码完全是愚蠢的,因为您正在创建变量layerWidthlayerHeight并将其丢弃,这是没有意义的。

Second, self.bounds.size is always the view's width and height. 其次, self.bounds.size始终是视图的宽度和高度。 However, it is pointless to ask about this in initWithCoder: , which (as you have rightly seen) happens long before the view is put into the interface and even longer before the auto layout takes place that resizes it. 但是,在initWithCoder:询问此问题毫无意义,正如您所正确看到的那样,它发生在将视图放入接口之前很久,甚至发生在自动调整视图大小之前。 If your drawing code relies on the bounds size, then retrieve the bounds size when you draw . 如果您的绘图代码依赖于边界大小,则在绘制时检索边界大小。 If you need to draw again because the view has changed size, and if this is not happening all by itself, then implement layoutSubviews to tell the view that it needs to be drawn again. 如果由于视图大小已更改而需要再次绘制,并且如果这不是全部发生,则实现layoutSubviews告诉视图需要再次绘制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM