【发布时间】:2017-06-20 13:56:32
【问题描述】:
有大量与此主题相关的问题,但我还没有遇到我的用例,所以这里是。
这是我在 OBJ-C 的头几周,所以我不知道我在用这些东西做什么......
我想要什么
我并不特别喜欢在 OBJ-C 中看到如此多的类,这些类使视图控制器类超载了地球上的所有功能。就 OOP 而言,它看起来很脏,感觉很恶心。在我的用例中,我没有一个全屏桌子,只有一个可以容纳 10 件东西的小桌子。因此使用完整的 UITableViewController 是非常不合适的。相反,我想让我的所有表委托特定方法都在 UITableView 子类中。不在 UITableViewController 或具有 UITableView 属性的 ViewController 中。这应该非常简单......
问题
无论我做什么,我似乎都无法触发 cellForRowAtIndexPath 方法。我知道这些东西在很大程度上依赖于委托和数据源分配......但是,由于我有一个单独的 UITableView 类,它使用 <UITableViewDelegate, UITableViewDataSource> 委托,我认为我根本不需要做任何类型的分配!
我要写什么?? self.delegate = self ?或者更糟糕的是,在调用这个 UITableView 类的 ViewController 中,self.tasksTable.delgate = self.tasksTable ?呃……恶心
这是我在代码中所做的。
守则
TasksTableView.h
#import <UIKit/UIKit.h>
@interface TasksTableView : UITableView <UITableViewDelegate, UITableViewDataSource> {
NSArray *tasksData;
}
- (NSMutableArray *)getAllTasks;
@end
TasksTableView.m
#import "TasksTableView.h"
#import "NSObject+RemoteFetch.h" //<--I use this to fetch, obvs
@interface TasksTableView ()
@property (nonatomic, strong) NSString *cellId;
@end
@implementation TasksTableView
- (instancetype)initWithCoder:(NSCoder *)coder {
self = [super initWithCoder:coder];
if(self) {
_cellId = @"AllTasksTableCell";
tasksData = [self getAllTasks];
}
return self;
}
#pragma mark - Custom Table Functionality
- (NSMutableArray *)getAllTasks {
@try {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *TASKS_URL = [userDefaults objectForKey:@"tasksUrl"];
NSObject *fetcher = [[NSObject alloc] init];
NSDictionary *response = [fetcher fetchAPICall:TASKS_URL httpRequestType:@"GET" requestBodyData:nil];
return [response objectForKey:@"data"];
} @catch (NSException *exception) {
NSLog(@"could not get tasks, error: %@", exception);
return nil;
}
}
#pragma mark - UITableView DataSource Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [tasksData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//<-- NEVER GETS HERE
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:_cellId];
if(cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:_cellId];
}
cell.textLabel.text = [tasksData objectAtIndex:indexPath.row];
return cell;
}
@end
我也很难弄清楚将什么设置为数据源。在其他语言中,您通常会将 DataSource 对象设置为 self.DataSource = [self getAllTasks]... 但是到目前为止我所做的所有教程都倾向于使用一些奇怪的临时 NSArray 或 NSDictionary 来将表函数的索引与索引相关联数组或字典键...这让我非常困惑,为什么我不能只设置 DataSource 对象并让表知道迭代它的数据。
我的结论是这不会触发,因为它认为 DataSource 对象是空的并且没有行? (确实如此,但就像我说的那样,人们似乎可以让 Tables 在 YouTube 上正常工作)
谢谢。
【问题讨论】:
-
在
initWithCoder:,尝试做self.dataSource = self。 -
我真的很希望这不是答案 :( 看起来太恶心了。
-
@Larme 是的,做到了 :( 提交答案,以便我投票并最终确定这个问题。谢谢
-
您需要了解的是,您需要 2 个对象来处理 UITableView:一个对象将作为数据源,另一个对象将作为委托。它可以是另一个对象,尤其是
self,但是由于您在文件TasksTableView中写了cellForRowAtIndexPath:,所以数据源应该是self。 -
是的,它看起来和感觉都非常恶心。谢谢。如果你能把这个写成答案,我可以帮你核对一下。
标签: ios objective-c uitableview datasource