重用 UITableView 及其 UI/delegate 方法



我有 2 个UIViewControllers,这两个包含完全相同的UITableView(带有自定义单元格和委托方法)。我的问题是他们有什么方法可以"集中"UITableView UI 和代码(数据源和委托),这样我只需要在一个文件中修改而不是 2 个。

跟进我的评论,你父亲 VC 中 XIB 中的表视图和你父亲 VC 中的委托方法只是在同一个地方,因为你选择它是这样的,表视图和委托方法实际上是非常分离的。

因此,创建一个新对象,例如实现UITableViewDatasourceUITabelViewDelegate FatherTableController并将这些方法从您的FatherViewController复制到此FatherTableController

现在在你的父亲视图控制器中,像

FatherTableController tableController = [FatherTableController new]; //should be a property or a singleton
self.tableview.delegate = tableController;
self.tableview.datasource = tableController;

现在,您可以在使用同一表的两个单独 VC 中执行此操作,甚至可以在两个视图之间使用相同的表控制器(可能通过单例模式,这对于在两个视图控制器之间共享状态很有用)

解决方案:

@interface FatherViewController : UIViewController <UITableViewDataSource,UITableViewDelegate>
@property (strong, nonatomic) IBOutlet UITableView *parentTableView;
@implementation FatherViewController
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.parentTableView.delegate=self;
        self.parentTableView.dataSource=self;
    }
    //declare the delegate / datasource methods

---------------------子视图控制器

---------------------
@interface ViewController : FatherViewController 
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        return [super tableView:tableView cellForRowAtIndexPath:indexPath];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [super numberOfSectionsInTableView:tableView];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [super tableView:tableView numberOfRowsInSection:section];
}

最新更新