菜鸟教程小白 发表于 2022-12-13 07:13:37

ios - awakeFromNib 与 drawRect 中的 CALayer


                                            <p><p>我很困惑,为什么下面的代码我加到<code>awakeFromNib</code>或者<code>initWithFrame:</code>里面可以用,但是我加到<code>drawRect:</code> 还是直接调用?</p>

<pre><code>self.layer.cornerRadius = CGRectGetWidth(self.bounds) / 2.0f;
self.layer.shadowColor = .CGColor;
self.layer.shadowRadius = 3;
self.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
self.layer.shadowOpacity = 0.75f;
</code></pre>

<hr/>

<p>对于以编程方式创建的按钮,我应该将此方法添加到哪里?按钮可能只使用 <code>init</code> 创建,然后通过约束更改大小。</p>

<p><strong>规范</strong>:通过工作,我的意思是按钮将是圆形的(如果纵横比为 1:1,则为圆形)并带有阴影。不工作,我的意思是它仍然是一个正方形。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>查看<a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/index.html#//apple_ref/occ/instm/UIView/drawRect:" rel="noreferrer noopener nofollow">the Apple Docs</a>中的详细说明,但本质上是因为您在绘制周期的中间设置图层配置(cornerRadius、阴影等),而您应该在绘制周期开始之前完成此设置。</p>

<p>来自 drawRect: 文档:</p>

<blockquote>
<p>By the time this method is called, UIKit has configured the drawing environment appropriately for your view and you can simply call whatever drawing methods and functions you need to render your content. </p>
</blockquote>

<p>其他函数,如 <code>awakeFromNib:</code> 或 <code>initWithFrame:</code> 在绘制周期之前发生,这意味着您的配置将在它们呈现在屏幕上之前被考虑在内。相比之下,<code>drawRect:</code> 假设这些基本配置已设置好,并且仅用于渲染您在屏幕上指定的内容。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - awakeFromNib 与 drawRect 中的 CALayer,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/30259342/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/30259342/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - awakeFromNib 与 drawRect 中的 CALayer