Objective C连接UITableViewController与UITableview编程或使用仪表板



我是新的目标c。我有一个UIView和我正在添加编程的UITableView。我有一个UIViewController,但我不想用它来操纵和显示数据给UITableView。我创建了一个UITableViewController的子类来操作数据并将它们显示给UITableView。我试图了解如何连接我的自定义UITableViewController到UITableView编程或通过使用故事板。

上述场景可能吗?

我唯一能做到的就是直接从storyboard中使用UITableViewController。

一般来说,表视图DataSource和Delegate方法已经很好地分割到MVC设计模式中了。

你可能想去谷歌(或你最喜欢的搜索引擎)搜索model view controller design pattern with uitableview。有很多文章/博客/例子/讨论/等等,最好先通读一遍。

你也可能会发现使用Objective-CCategory将是一个更好的方法。

然而,这里有一个非常非常简单的例子,使用一个单独的类作为你的表视图的数据源和委托:

MyTableHandler.h

//  MyTableHandler.h
#import <UIKit/UIKit.h>
@interface MyTableHandler : NSObject <UITableViewDataSource, UITableViewDelegate>
@end

MyTableHandler.m

//  MyTableHandler.m
#import "MyTableHandler.h"
@implementation MyTableHandler
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 20;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *c = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
NSString *s = [NSString stringWithFormat:@"Row: %ld", indexPath.row];
c.textLabel.text = s;
return c;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"Row %ld selected!", (long)indexPath.row);
// How do we tell the VIEW CONTROLLER the row was selected?
// We have to use either protocol / delegate pattern, or
//  we have to pass Blocks
}
@end

MyViewController.h

//  MyViewController.h
#import <UIKit/UIKit.h>
@interface MyViewController : UIViewController
@end

MyViewController.m

//  MyViewController.m
#import "MyViewController.h"
#import "MyTableHandler.h"
@interface MyViewController ()
{
UITableView *tableView;
MyTableHandler *myTableHandler;
}
@end
@implementation MyViewController
- (void)viewDidLoad {
[super viewDidLoad];

self.view.backgroundColor = [UIColor systemYellowColor];

tableView = [UITableView new];
tableView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:tableView];

UILayoutGuide *g = self.view.safeAreaLayoutGuide;

[NSLayoutConstraint activateConstraints:@[

// constrain tableView 80-pts from top (safe area)
//  20-pts leading / trailing / bottom (safe area)
[tableView.topAnchor constraintEqualToAnchor:g.topAnchor constant:80.0],
[tableView.leadingAnchor constraintEqualToAnchor:g.leadingAnchor constant:20.0],
[tableView.trailingAnchor constraintEqualToAnchor:g.trailingAnchor constant:-20.0],
[tableView.bottomAnchor constraintEqualToAnchor:g.bottomAnchor constant:-20.0],

]];
[tableView registerClass:UITableViewCell.class forCellReuseIdentifier:@"cell"];

// instantiate MyTableHandler
myTableHandler = [MyTableHandler new];
tableView.dataSource = myTableHandler;
tableView.delegate = myTableHandler;

}
@end

最新更新