【问题标题】:Sharing code between UITableViewCell and UICollectionViewCell在 UITableViewCell 和 UICollectionViewCell 之间共享代码
【发布时间】:2013-04-02 07:47:19
【问题描述】:

我有一个相当大的 UITableViewCell 子类,它处理各种手势和统计行为。 我还在构建一个 UICollectionView,我的 UICollectionViewCell 子类行为非常接近我的 UITableViewCell。我已经粘贴了很多代码。

我的问题是:是否有一种设计模式可以让我在这两个子类之间共享 UI 代码(手势和状态)?

我听说过构图模式,但我很难适应这种情况。使用正确的模式吗?

注意:我必须同时保留 UITableView 和 UICollectionView,因此删除 UITableView 不是解决方案。

【问题讨论】:

    标签: ios objective-c design-patterns uitableview uicollectionviewcell


    【解决方案1】:

    我认为,您可以在它们共同的祖先 UIView 上使用类别。只能共享通用方法,不能共享实例变量。

    让我们看看如何使用它。

    例如你有自定义 UITableViewCell

    @interface PersonTableCell: UITableViewCell
    @property (nonatomic, weak) IBOutlet UILabel *personNameLabel;
    - (void)configureWithPersonName:(NSString *)personName;
    @end
    
    @implementation PersonTableCell
    - (void)configureWithPersonName:(NSString *)personName {
        self.personNameLabel.text = personName;
    }
    @end
    

    还有 UICollectionViewCell

    @interface PersonCollectionCell: UICollectionViewCell
    @property (nonatomic, weak) IBOutlet UILabel *personNameLabel;
    - (void)configureWithPersonName:(NSString *)personName;
    @end
    
    @implementation PersonCollectionCell
    - (void)configureWithPersonName:(NSString *)personName {
        self.personNameLabel.text = personName;
    }
    @end
    

    两个共享通用方法 configureWithPersonName: 到他们的祖先 UIView 让我们创建类别。

    @interface UIView (PersonCellCommon)
    @property (nonatomic, weak) IBOutlet UILabel *personNameLabel;
    - (void)configureWithPersonName:(NSString *)personName;
    @end
    
    @implementation UIView (PersonCellCommon)
    @dynamic personNameLabel; // tell compiler to trust we have getter/setter somewhere
    - (void)configureWithPersonName:(NSString *)personName {
        self.personNameLabel.text = personName;
    }
    @end
    

    现在在单元实现文件中导入类别标题并删除方法实现。从那里您可以使用类别中的常用方法。 唯一需要复制的是属性声明。

    【讨论】:

    • 如果你添加一些例子会很有用;)
    猜你喜欢
    • 1970-01-01
    • 2014-09-24
    • 2014-07-07
    • 1970-01-01
    • 1970-01-01
    • 2011-03-02
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多