1

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

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

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

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

回答

4

我想,你可以在他们的共同祖先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 

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

+0

如果你添加一些例子,这将是有用的;) –

相关问题