OGeek|极客世界-中国程序员成长平台

标题: ios - 具有可选 IBOutlet 的属性多态性 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 13:26
标题: ios - 具有可选 IBOutlet 的属性多态性

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

   ====================
  | BaseCellWithButton |
   ====================
            ^
            |
            |
 ========================
| BaseCellWithTwoButtons |
 ========================

BaseCellWithButton 有 1 个属性:

@property (nonatomic, strong) UIButton* button;

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

这是一种不好的做法吗?有没有更好的方法来实现多态,同时允许子类创建一个 nib 并仍然重用父属性?



Best Answer-推荐答案


您可以在 BaseCellWithButton 类中将 button 声明为 IBOutlet,然后只需在任何子类中从 xib 连接按钮。

enter image description here

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

有基类和子类。

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

在基类中,声明了 button 但它仅在子类中连接到 xib https://dl.dropboxusercontent.com/u/48223929/SubclassTableCellsExample.zip

关于ios - 具有可选 IBOutlet 的属性多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27692007/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4