[英]UITableView delegate and datasource in UITableViewCell
我在UITableViewCell中有一個UITableView,我需要弄清楚如何設置子表視圖數據源和委托。 目前,這是我所擁有的:
MainTableViewController.h
#import <UIKit/UIKit.h>
@interface MainTableViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate>
@end
MainTableViewController.m
#import "MainTableViewController.h"
#import "TableViewCell.h"
@interface MainTableViewController ()
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@end
@implementation MainTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - UITableView delegate functions
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 3;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"tableViewCell";
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
cell.cellLabel.text = [NSString stringWithFormat:@"%ld", (long)indexPath.row];
return cell;
}
@end
TableViewCell.h
#import <UIKit/UIKit.h>
@interface TableViewCell : UITableViewCell <UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UILabel *cellLabel;
@property (weak, nonatomic) IBOutlet UITableView *subTableView;
@end
TableViewCell.m
#import "TableViewCell.h"
@implementation TableViewCell
-(id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
self.subTableView.delegate = self;
self.subTableView.dataSource = self;
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"subTabeViewCell"];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"subTabeViewCell"];
cell.textLabel.text = @"test";
return cell;
}
@end
因為無法ctrl +從子表視圖拖動到TableViewCell類,所以我試圖在初始化過程中以編程方式設置委托和數據源,但是它無法正常工作,我只是感到困惑。
我知道我可以設置數據源和委托以連接到第一個類,然后在每個委托函數中檢查我正在處理的tableView,但是我嘗試執行的操作具有這種特性。確實有效,我已經嘗試過。
因此歡迎所有幫助
所以我想通了,好了我想出了一種方法。 在MainTableViewController.m的cellForRowAtIndexPath中,我簡單地添加了:
[cell.subTableView setDelegate:cell];
[cell.subTableView setDatasource:cell];
一切都在努力
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.