我想,你可以在他们的共同祖先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
现在在单元实现文件中导入类别标题并移除方法实现。从那里你可以使用类别中的常用方法。 您需要重复的唯一事情是属性声明。
如果你添加一些例子,这将是有用的;) –