简体   繁体   中英

UIViewController, UITableView, Protocol

I have a UIViewController , which has a

 @interface MYViewController : UIViewController<UITableViewDelegate>

  @property (weak, nonatomic) IBOutlet UITableView *tblView;

Now I am implementing the UITableViewDelegate because I want to use the tableview.

so in my viewdidload I do

- (void)viewDidLoad
  {
   [super viewDidLoad];
    self.tblView.delegate = self;
    //self.tblView.dataSource = self;
  }

Now the Datasource setting throws a warning, and I never hit the

cellForRowAtIndexPath

method.

Sorry about the editing.

What am I doing wrong?

you need

self.tblView.datasource = self;

also adopt to UITableViewDatasource Protocol,

@interface MYViewController : UIViewController<UITableViewDelegate,UITableViewDatasource>

cellForRowAtIndexPath is a datasource method.

Your interface should also implement the UITableViewDataSource protocol.

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

Please try as below.. UIViewController.h

@interface MYViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>
  @property (Strong, nonatomic) IBOutlet UITableView *tblView;

please don't forget to connect tblView outlet to tableView in your .xib file, since this is very required otherwise your datasource methods won't get called.

In UIViewController.m file

  - (void)viewDidLoad {  [super viewDidLoad];
self.tblView.delegate = self;
self.tblView.dataSource = self; }

and implement two required datasource methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return (number of row you want in table)}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ return cell }

surely this will work for you.

For UITableViewDatasource Protocol add UITableViewDatasource to

@interface MYViewController : UIViewController<UITableViewDelegate, UITableViewDatasource>

and add this line to viewDidLoad

self.tblView.datasource = self;

and go to your storyboard and link 'datasource' and 'delegate' to your tblView

There are couple of problems in your implementation.

  1. You are not conforming to UITableViewDatasource protocol.
  2. You are not setting tableview datasource.
  3. You are not implementing UITableViewDatasource protocol's required methods

You cannot expect to work without setting datasource.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM