【问题标题】:Set delegate to an object将委托设置为对象
【发布时间】: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


【解决方案1】:

什么是 vTable?看起来你有一个“voteTable”类(顺便说一句:类应该以大写字符开头,实例变量应该以小写开头)。无论如何,看起来您的主要问题是您忘记将表格添加为子视图并设置其框架。例如:

self.voteTbl = [[VoteTable alloc] init];
self.voteTbl.delegate = self;
self.voteTbl.dataSource = self;
self.voteTbl.frame = self.view.bounds;
[self.view addSubView:self.voteTbl];

【讨论】:

  • 谢谢!我没有意识到离开 IB 会有多么不同......使用这种方法我会失去 IB 的所有控制权(拖放定位)吗?有什么办法可以将它链接到我在 IB 中制作的表格?它们具有相同的参考出口。
  • 您仍然拥有完全的控制权——您需要设置框架,使其以您想要的位置/大小显示。您还可以以编程方式使用自动布局约束。例如:stackoverflow.com/questions/15893022/…
  • @johnhannigan - 您可以在 IB 中链接到您的 VoteTable 课程。 IIRC(每次我都必须对此感到困惑)您在 IB 中选择了一个 TableView,但在右侧的选项卡中将其类更改为 VoteTable。 (当然,您仍然需要自己设置委托和数据源。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-19
  • 1970-01-01
相关资源
最近更新 更多