gpt4 book ai didi

iphone - 将 UITableView 的委托(delegate)/数据源与主 ViewController 分开

转载 作者:太空狗 更新时间:2023-10-30 03:52:34 24 4
gpt4 key购买 nike

我是 iOS 开发的新手。我已经阅读了有关 ViewControllers 变得巨大的问题,并且想遵循我在上一个问题 UITableView issue when using separate delegate/dataSource 的答案中看到的设计,我的应用程序在一个屏幕上有 2 个不同的表格和几个按钮.但不知何故,我对 TestTableViewController 和 TestTableTestViewController 之间的 Storyboard连接感到困惑。

谁能提供一个示例工作项目或一些屏幕截图,说明如何将 UITableView 委托(delegate)、数据源和连接 socket 连接到单独的自定义 UIViewController 子类(TestTableTestViewController) 在 Storyboard 中好吗?

此外,此设计是否适用于 xCode 5/iOS 7 及更高版本?

注意:对于那些已经迁移到 Swift 的人,我强烈建议对委托(delegate)和数据源使用 Swift 扩展,事实上,根据 Natasha The Robot 博客文章 here < 的“分组”部分,继承类或协议(protocol)的任何其他实现/p>

最佳答案

您必须创建另一个名为 MyTableViewDataSource 的类,并在其中实现 TabbleViewDataSource 方法。创建数据源类的属性。在 ViewController 中设置数据源这是例子:

@interface MyTableViewDataSource ()
@property (nonatomic, assign) int sectionOneRows;
@property (weak) id<YourDelegate> delegate;
@property (nonatomic, strong) NSArray *dataSourceArray;
@end

@implementation MyTableViewDataSource
@synthesize delegate=_delegate;

-(id) initDataSourceWithdArray:(NSArray *)array
delegate:(id)delegate
{
if (self = [super init]) {
self.dataSourceArray=array;
self.delegate = delegate;
}
return self;
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return numberOfRows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *cellToReturn = nil;
//Your code here
return cellToReturn
}

#pragma mark - UITableView Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
//Your logic here
//implement the delegate method in you ViewController
[self.delegate performSelector:@selector(loadDetailsAtIndexPath:)withObject:indexPath];
}
}

在你的ViewController中:

self.myDataSource = [[MyTableViewDataSource alloc] initDataSourceWithdArray:self.dataArray delegate:self];
[self.myTableView setDataSource:self.myDataSource];
[self.myTableView setDelegate:self.myDataSource];
[self.myTableView reloadData];

您的委托(delegate)方法:

-(void)loadDetailsAtIndexPath:(NSIndexPath *)indexPath
{
MyDetailViewController *myDetailController = [[MyDetailViewController alloc] initWithNibName:@"MyDetailViewController" bundle:nil];
//Your logic here
[self.navigationController pushViewController:myDetailController animated:YES];
}

转到连接检查器并进行如下更改:

enter image description here

tableView 的数据源将在此处以编程方式设置,而不是在 IB 中设置。我希望这能帮到您。

关于iphone - 将 UITableView 的委托(delegate)/数据源与主 ViewController 分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24430386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com