Sharing code between UITableViewCell and UICollectionViewCell

瘦欲@ 提交于 2019-12-11 11:13:14

问题


I have a pretty big UITableViewCell subclass which handle various gestures and stat behavior. I'm also building a UICollectionView, my UICollectionViewCell subclass behavior is pretty close to my UITableViewCell. I've pasted a lot of code from it.

My questions is: Is there is a design pattern that would allow me to have the UI code (gesture and state) shared between those 2 subclasses ?

I've heard of the composition pattern, but I have hard time fitting it for this case. Is it the right pattern to use ?

Note: I MUST keep both UITableView and UICollectionView, so dropping the UITableView is not a solution.


回答1:


I think, you can use category on their common ancestor UIView. You can only share common methods, not instance variables.

Lets see how to use it.

For example you have custom 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

And 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

Two share common method configureWithPersonName: to their ancestor UIView lets create category.

@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

Now import category header in cell implementation files and remove method implementations. From there you can use common method from category. The only thing that you need to duplicate is property declarations.



来源:https://stackoverflow.com/questions/15758787/sharing-code-between-uitableviewcell-and-uicollectionviewcell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!