ios - 将委托(delegate)设置为对象

标签 ios objective-c delegates

这是我第一次尝试将 UITableView 委托(delegate)/数据源设置为对象的实例。

我有一个由名为 hMain 的类管理的 UIView,以及由名为 vTable 的类的实例管理的 main 内部的 UITableView。

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 并以编程方式做事,所以我不确定我设置的委托(delegate)和事情是否正确。这也是我第一次尝试在自身之外设置委托(delegate)/数据源。

我的问题是表格每次都是空白的。

最佳答案

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

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

关于ios - 将委托(delegate)设置为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18424186/

相关文章:

iOS SDK - subview 和操作

ios: 如何将 html 数据转换为 nsstring?

objective-c - NSMutableDictionary 不保留值

ios - 通过委托(delegate)关闭其呈现的模态视图 Controller 后刷新 UIViewController 中的数据

C# 委托(delegate)给具有不同可选参数的方法

IOS7 - 自动布局屏幕宽度

ios - 如何获取另一个应用程序当前正在播放的音频

ios - 将 UIImage 裁剪到自定义路径并保持正确的分辨率?

objective-c - epub2pdf分页html格式

Scala 委托(delegate)导入隐式转换