[英]iOS - Reuse exact same cell design and code in multiple views
我的應用程序中有4個不同的視圖,當前顯示完全相同的UITableViewCell。 在我的故事板中,我有4次出現相同的單元格(這是一個相當復雜的自定義單元格),在.m文件中,我或多或少地將完全相同的代碼將數據關聯到UITableViewCell。
我知道這是一種錯誤的方法 - 維護和更新非常困難。
在故事板中集中UITableViewCell的正確方法是什么,並集中填充表的代碼,以便我可以在不同的視圖中重用它?
我個人認為在代碼中編寫所有視圖是達到最大可重用性(和可擴展性,因為nib文件不能被子類化)的最佳方法。 但我認為您也可以為UITableViewCell創建一個單獨的nib並將其加載到每個視圖控制器中。 我認為無論采用哪種方法(在代碼中完全設計單元格,或借助nib文件),您都可以在viewDidLoad
中的代碼中加載單元格,使用類似的方法:
[self.tableView registerClass:MyCustomCell.class forCellReuseIdentifier:@"Cell"];
以上是我最常使用的,因為我喜歡在代碼中編寫所有視圖,顯然對於加載nib,你可以參考dirtydanee描述的方法。
然后,您的tableView將在-cellForRowAtIndexPath:
加載具有相同標識符的單元格-cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
// configure your cell here ...
return cell;
}
我建議為你的UITableViewCell
子類創建一個Xib
文件,並在其上聲明一個configuration(_:)
函數。 此函數可以使用任何參數,例如字典。 但是,您可以提供包含參數, struct
可能或您正在使用的任何數據類型的特定數據模型。
ReusableTableViewCell.h
#import <UIKit/UIKit.h>
@interface ReusableTableViewCell: UITableViewCell
@property(nonatomic, weak) IBOutlet UILabel* title;
@property(nonatomic, weak) IBOutlet UILabel* subTitle;
/// - Parameter configuration: It is a dictionary at the minute
/// However, it could be any type, you could even be creating your own model struct or class
- (void)configureWith:(NSDictionary *)configuration;
@end
ReusableTableViewCell.m
#import "ReusableTableViewCell.h"
@implementation ReusableTableViewCell
- (void)configureWith:(NSDictionary *)configuration {
self.title.text = configuration[@"title"];
self.subTitle.text = configuration[@"subTitle"];
}
- (void)prepareForReuse {
[super prepareForReuse];
self.title.text = nil;
self.subTitle.text = nil;
}
@end
將nib
注冊到tableView
。 重要的是,不要將其注冊為class
,將其注冊為nib
。
[tableView registerNib: [UINib nibWithNibName:@"yourCellNibName" bundle:nil] forCellReuseIdentifier:@"yourReuseIdentifier"];
在您的cellForRowAtIndexPath
的最后,只需獲取配置並將其提供給tableViewCell
。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// create your cell
ReusableTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"yourReuseIdentifier"];
// get your configuration
NSDictionary *configuration = [configurations objectAtIndex:indexPath.row];
//configure your cell
[cell configureWith: configuration];
return cell;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.