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

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

相關問題