[英]Xcode: add TableView into custom Cell
我正在嘗試做某事,但都沒有在網絡上找到任何示例,也不知道是否有可能。
我需要以編程方式將表添加到tbaleview的第一個單元格中。
當我嘗試設置第二個表(第一個表中的一個)的委托和數據源時,代碼給我帶來了問題
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
[[NSBundle mainBundle] loadNibNamed:@"CellaMenu" owner:self options:NULL];
cell = cellaMenu;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.userInteractionEnabled = NO;
tabellaMenu = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
tabellaMenu.dataSource = self;
tabellaMenu.delegate = self;
[cell.contentView addSubview:tabellaMenu];
}
這樣,代碼循環。 如果不設置委托和數據源,則將顯示該表,但我需要它們來創建自定義處理程序。 有什么提示嗎?
最干凈的方法是在視圖控制器中具有另一個符合UITableViewDataSource和UITableViewDelegate的對象,然后將第二個表視圖的委托和dataSource設置為此對象。
代碼進入循環,因為單元格中的tabellaMenu表已將委托和數據源設置為self。 因此,它繼續自行調用表數據源方法,並創建新的單元格並進入循環。
您可以創建一個單獨的對象(NSObject的子類),然后在其中定義表委托和數據源方法,並將其設置為tabellaMenu的委托和數據源。
或者,您可以創建UITableViewCell的子類並以編程方式在其中創建表視圖。 定義表的數據源並在其中委托方法。 因此,該單元格中的每個表視圖都將引用其自己的單元格進行數據源和委托。 此外,每次主表重新加載時,您都會獲得-(void)prepareForReuse(如果單元格可重用)以在單元格中重新加載表。
在-tableView:cellForRowAtIndexPath:
內部,您可以在創建單元格后編寫以下代碼。
//if first row & table is not present already
if (indexPath.row == 0 && ![cell.contentView viewWithTag:5]) {
UITableView *tabellaMenu =
[[UITableView alloc] initWithFrame:self.contentView.bounds
style:UITableViewStylePlain];
tabellaMenu.tag = 5;
tabellaMenu.dataSource =tabellaMenuDataSource;
tabellaMenu.delegate = tabellaMenuDelegate;
[cell.contentView addSubview:tabellaMenu];
}
方法如下:
如果僅在第一個單元格中需要tableView
,則可以全局使用它,而不必在cellForRowAtIndexPath:
方法中進行初始化,因為它在滾動期間每次都被調用。
UITableView *mainTableView;
UITableView *childTableView;
現在,您可以通過比較它們的實例,輕松地在它們的delegates
和datasources
方法中區分這兩個表。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
if (tableView == mainTableView) {
// Do code for your main tableView
if (indexPath.row == 0) {
[[NSBundle mainBundle] loadNibNamed:@"CellaMenu" owner:self options:NULL];
cell = cellaMenu;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.userInteractionEnabled = NO;
if (!childTableView) {
// Initialise only if it is nil (not initialised yet)
childTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
childTableView.dataSource = self;
childTableView.delegate = self;
}
[cell.contentView addSubview:childTableView];
}
}
else {
// Do code for your child tableView
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.