[英]How to add Section and TableView Cell dynamically
我有一個按鈕,當按下該按鈕時,將添加一個tableview部分,並且還會向該部分添加一個新行。 我怎么能以編程方式實現這個呢?
我有一系列細胞。
這是我的代碼
- (IBAction)addCell:(id)sender {
UITableViewCell *newCell = [[UITableViewCell alloc] init];
counter++;
[cells addObject:newCell];
[self.tableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [cells count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//this is where i want to adjust the row per section
//this code hide the recent sections, only the current created section appears
return [cells objectAtIndex:indexPath.row];
}
您只需將新部分和新項目添加到包含該部分的數組和類似的項目:
- (void)viewDidLoad
{
[super viewDidLoad];
animals = @{@"Section 1" : @[@"Item 1", @"Item 2", @"Item 3"],
@"Section 2" : @[@"Item 1", @"Item 2"]};
}
之后,只需在邏輯需要的地方重新加載tableView:
[self.tableView reloadData];
首先,更新您的數據模型(NSArray或mutable)。 其次,當你想要tableview刷新時,添加一個代碼[self.tableView reloadData];
oops,你的代碼有些奇怪的uitaleviewDataSource,Delegate方法。
還有,你有一些錯誤。
為什么你實現numberOfRowsInSection返回1? 很奇怪。
我贊賞下面的代碼。
案例1.沒有DataModel。
- (IBAction)addCell:(id)sender
{
cellRowsCount++;
[self.tableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return cellRowsCount;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
return cell;
}
您的代碼,dataModel(NSArray或mutable)不一定需要,所以我只是添加了rowCount變量,並且tableviewCell的rowsCount已經同步。
如果你想使用DataModel,請在CASE2下面。 請參閱plz。
CASE2。 有DataModel。
- (IBAction)addCell:(id)sender
{
textCount ++;
NSString *cellText = [NSString stringWithFormat:"blah %d", textCount];
[myArray addObject:cellText];
[self.tableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [myArray count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[myArray objectAtIndex:section] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = (NSString *)[myArray objectAtIndex:indexPath.row];
return cell;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.