如何设置一个tableview委托

我试图使用UITableView而不使用一个笔尖,也没有使用UITableViewController

我已经添加了一个UITableView实例到像这样的UIViewController

 mytable = [[UITableView alloc] initWithFrame:CGRectMake(22, 207, 270, 233)]; [mytable setDelegate:self]; [self.view mytable]; 

此外,我已经添加了下面的表视图方法到我的UIViewController (cut为重点)

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

我得到一个警告,说我的UIViewController不实现UITableView委托协议。

什么是正确的方式来告诉表视图委托方法的地方?

(这是我第一次尝试使用UITableView而不从新的文件选项中selectUITableTableview控制器)

你需要使你的类符合UITableViewDelegateUITableViewDataSource协议。 ( cellForRowAtIndexPath:UITableViewDataSource协议中)

在你的类接口定义中使用尖括号来做到这一点:

 @interface myViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {...} 

你现在得到这个警告,而不是在你使用UITableViewController之前,是因为UITableViewController已经符合这些协议。

所以,本质上UITableViewController只是一个符合UITableViewDelegateUITableViewDataSource ,并且有一个UITableView实例成员。 这是非常多的。

当然,如果你还没有UITableViewController ,那么你需要手动设置UITableViewdataSourcedelegate

 [tableView setDelegate:self]; [tableView setDataSource:self]; 

您还必须将dataSource委托设置为self:

 [tableView setDelegate:self]; [tableView setDataSource:self]; 

或者同样:

 tableview.delegate = self; tableview.dataSource = self; 

警告只是告诉你,你的@interface部分应该声明你实现了UITableViewDelegate协议:

 @interface MyUIViewController : UIViewController < UITableViewDelegate > 
 [tableview setDataSource:self] 

你必须明确地说,为什么因为UITableView的两个必需的方法是在UITableViewDataSource协议下。

 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section; - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; 

在Swift3中这是你如何设置UITableViewDelegate

 class FeedsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var feedsTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() feedsTableView.delegate = self feedsTableView.dataSource = self // Do any additional setup after loading the view. } }