【发布时间】:2013-08-24 23:30:17
【问题描述】:
这是我第一次尝试将 UITableView 委托/数据源设置为对象的实例。
我有一个 UIView 由一个名为 hMain 的类管理,一个 UITableView 在 main 内部由一个名为 vTable 的类的实例管理。
hMain.h:
@interface hMain : UIViewController
@property (strong, nonatomic) IBOutlet vTable *voteTbl;
@end
hMain.m:
- (void)viewDidLoad
{
[super viewDidLoad];
voteTbl = [[vTable alloc]init];
[self.voteTbl setDelegate:voteTbl];
[self.voteTbl setDataSource:voteTbl];
}
vTable.h:
@interface vTable : UITableView <UITableViewDelegate , UITableViewDataSource>
@end
vTable.M:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 5;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [UITableViewCell configureFlatCellWithColor:[UIColor greenSeaColor] selectedColor:[UIColor wetAsphaltColor] reuseIdentifier:CellIdentifier inTableView:(UITableView *)tableView];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[cell configureFlatCellWithColor:[UIColor greenSeaColor] selectedColor:[UIColor wetAsphaltColor]];
}
cell.textLabel.text = @"Hello there!";
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"Row pressed!!");
}
这真的是我第一次偏离 IB 并以编程方式做事,所以我不确定我是否正确设置了委托和事情。这也是我第一次尝试在 self 之外设置委托/数据源。
我的问题是表格每次都是空白的。
【问题讨论】:
-
我在您的代码中没有看到您设置 voteTable 的框架或将其添加到视图中的任何地方。
-
表格视图不应该是它自己的委托,因为这违反了 MVC 原则。您应该有一个 UIViewController 子类或 UITableViewController 子类作为委托。
-
@rdelmar - 然而这是 Objective-C 中非常常见的模式,世界并没有因此而分崩离析。
-
@HotLicks,我的意思是在我的评论中说数据源不是委托。将表视图作为自己的数据源肯定是一种糟糕的 MVC 做法。
-
@rdelmar - 为什么?仅仅因为它“违反了 MVC”?哎呀,没有人真正关注 MVC,尽管很多人只是口头上说。
标签: ios objective-c delegates