Dimillian
Dimillian

Reputation: 3656

Sharing code between UITableViewCell and UICollectionViewCell

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.

Upvotes: 3

Views: 1922

Answers (1)

user2216460
user2216460

Reputation:

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.

Upvotes: 4

Related Questions