2011-12-26 2 views
0

Я хочу добавить UIButton в ячейку таблицы динамически - см. Ниже требования.Как добавить UIButton в UITableViewCell динамически?

Когда пользователь выбирает ячейку, я просто регулировать высоту этой ячейки таблицы в

-(void) tableView:(UITableView*) tableView didSelectRowAtIndexPath:(UIIndexPath*) indexPath { 
     selIndPath = [indexPath retain]; 
     [self.tableView beginUpdates]; 
     [self.tableView endUpdates]; 
} 

Приведенный выше метод заставляет Tableview регулировать высоту этой выбранной строки. Но когда я добавил UIButton в вышеуказанный метод, кнопка не видна.

Меня не интересует [self.tableView reloadData];

Любая помощь очень ценится.

** * **EDITED* ** * ***

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (selIndPath && selIndPath == indexPath) { 
     //UITableViewCell* cell = [self tableView:tableView cellForRowAtIndexPath:indexPath]; 
//  UIButton* btn = (UIButton*)[[cell contentView] viewWithTag:1234]; 
//  btn.frame = CGRectMake(40, 60, 60, 24); 
//  [cell setNeedsDisplay]; 
     return 90; 
    } 
    return 64; 
} 

- (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] autorelease]; 
     [[cell contentView] setBackgroundColor:[UIColor clearColor]]; 
     [[cell backgroundView] setBackgroundColor:[UIColor clearColor]]; 
    } 

    // THIS LINES OF CODE WORKS ONLY ON reloadData 
    if (selIndPath && selIndPath == indexPath) { 
     UIButton* btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
     btn.frame = CGRectMake(40, 60, 60, 24); 
     btn.tag = 1234; 
     [btn setTitle:@"Hi" forState:UIControlStateNormal]; 
     [cell.contentView addSubview:btn]; 
    } 

    // Configure the cell. 
    cell.textLabel.text = @"Loading.."; 
    return cell; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    selIndPath = [indexPath retain]; 
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO]; 
    //[self.tableView reloadData]; 
    [self.tableView beginUpdates]; 
    [self.tableView endUpdates]; 
} 
+0

Можете ли вы показать код, который вы использовали, чтобы добавить UIButton? – Louis

+0

Спасибо за ответ, я добавил еще один дополнительный код на мой вопрос. Это может помочь вам понять это. – prathumca

ответ

2

Добавление кнопки не будет работать, если вы добавите его к ячейке в cellForRowAtIndexPath:. Что вам нужно сделать, это создать пользовательский UITableViewCell (Обратитесь к ответу на этот вопрос на how- Changing the position of custom UIButton in custom UITableViewCell)

В пользовательской ячейке создайте метод

-(void) addButtonToCell 
{ 
    UIButton* btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    btn.frame = CGRectMake(40, 60, 60, 24); 
    btn.tag = 1234; 
    [btn setTitle:@"Hi" forState:UIControlStateNormal]; 
    [self.contentView addSubview:btn]; 

} 

Конечно, как добавить кнопку и что аргументы, которые вы передаете этому методу, до вас, но вы получаете суть.

В cellForRowAtIndexPath: просто добавьте

if (selIndPath && selIndPath == indexPath) { 
[cell addButtonToCell]; 
} 
+0

Спасибо за ответ. Это работает тогда и только тогда, когда вы вызываете [tableView reloadData]. Как уже говорилось ранее, меня не интересует reloadData. Так как моя таблица имеет очень большие данные, она не влияет на изменение анимации строк. – prathumca

+0

@prathumca: как насчет использования этого метода - (void) reloadRowsAtIndexPaths: (NSArray *) indexPaths withRowAnimation: (UITableViewRowAnimation) анимация на вашем столе. Это будет перезагружать только те строки, которые вы хотите. – MadhavanRP

+0

Я пытался попробовать, но на данный момент не повезло. Анимация не так гладко, и кнопки не отображаются/выравниваются правильно. Любая помощь действительно ценится. – prathumca

Смежные вопросы