菜鸟教程小白 发表于 2022-12-12 13:26:28

ios - 具有可选 IBOutlet 的属性多态性


                                            <p><p>我的 iOS 项目中有一个 UITableViewCells 的多态链(为问题而简化):</p>

<pre><code>   ====================
| BaseCellWithButton |
   ====================
            ^
            |
            |
========================
| BaseCellWithTwoButtons |
========================
</code></pre>

<p>BaseCellWithButton 有 1 个属性:</p>

<pre><code>@property (nonatomic, strong) UIButton* button;
</code></pre>

<p>BaseCellWithTwoButtons 足够复杂,我想创建一个 Nib 。我知道 IBOutlet 属性通常是 <code>(nonatomic, weak) IBOutlet ...</code>,但我想将它声明为 <code>(nonatomic, strong) IBOutlet ...</code> 所以我可以选择在一个 nib 的子类中设置它,但如果没有,我可以在父类中实例化它。 </p>

<p>这是一种不好的做法吗?有没有更好的方法来实现多态,同时允许子类创建一个 nib 并仍然重用父属性?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>您可以在 <code>BaseCellWithButton</code> 类中将 <code>button</code> 声明为 <code>IBOutlet</code>,然后只需在任何子类中从 xib 连接按钮。</p>

<p> <img src="/image/meNJ3.png" alt="enter image description here"/> </p>

<p>我附上了示例文件,你可以将它添加到任何项目中,看看它是如何工作的。</p>

<p>有基类和子类。 </p>

<p>如果您计划通过父类中的代码实例化它,<code>strong</code> 引用也是最佳实践</p>

<p>在基类中,声明了 <code>button</code> 但它仅在子类中连接到 xib
<a href="https://dl.dropboxusercontent.com/u/48223929/SubclassTableCellsExample.zip" rel="noreferrer noopener nofollow">https://dl.dropboxusercontent.com/u/48223929/SubclassTableCellsExample.zip</a> </p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 具有可选 IBOutlet 的属性多态性,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/27692007/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/27692007/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 具有可选 IBOutlet 的属性多态性