2012-04-19 5 views
1

У меня есть сгруппированное представление таблицы, которое содержит 3 раздела, я хочу добавить разные кнопки для каждого раздела, у меня есть 5 ячеек в первом разделе, и я хочу добавить только 3 кнопки в 2-м, 3r и 4-й cell.my код выглядит так:Добавление UIButton в ячейки UItableview

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 3; 
} 


// Customize the number of rows in the table view. 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    if(section == 0) 
     return [_arayfirstrow count]; 
    else if(section == 1) 
     return [_arraysecondrow count]; 
    else if(section == 2) 
     return [_arraythirdrow count]; 
} 
    // Customize the appearance of table view cells. 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *CellIdentifier = @"Cell"; 
    // static NSUInteger nTag = 100; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; 
     cell.textLabel.font = [UIFont fontWithName:@"Georgia"size:20.0]; 



    } 

    // Set up the cell... 
    if(indexPath.section == 0){ 
      cell.textLabel.text = [_arayfirstrow objectAtIndex:indexPath.row]; 
     NSString *imageName = [_arayfirstrowimg objectAtIndex:indexPath.row]; 
     cell.imageView.image = [UIImage imageNamed:imageName]; 

**//when i add below code for inserting button on the first section ,it successfully adds the button,but i don't need button for 1st and 5th cell..ans also it crashes when i tap the button for 2 or three time** 

    CGRect buttonRect = CGRectMake(210, 25, 65, 25); 
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
     button.frame = buttonRect; 
     // set the button title here if it will always be the same 
     [button setTitle:@"Action" forState:UIControlStateNormal]; 
     button.tag = 1; 
     [button addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside]; 

     [cell.contentView insertSubview:button atIndex:0]; 



     // [usernamebutton release]; 

    }else if(indexPath.section == 1){ 
     cell.textLabel.text = [_arraysecondrow objectAtIndex:indexPath.row]; 
    } 
    else if(indexPath.section == 2) 
    { 
     cell.textLabel.text = [_arraythirdrow objectAtIndex:indexPath.row]; 

    } 
    return cell; 
} 

Если у вас возникли проблемы с решением проблемы. благодарит заранее.

+0

если вы перечисляете вы можете получить что-то другое., – Bala

ответ

2

Вы можете попробовать так:

if(indexPath.section == 0) 
{ 
    if(indexPath.row == 1||indexPath.row == 2||indexPath.row == 3) 
    { 
     CGRect buttonRect = CGRectMake(210, 25, 65, 25); 
     UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
     button.frame = buttonRect; 
     // set the button title here if it will always be the same 
     [button setTitle:@"Action" forState:UIControlStateNormal]; 
     button.tag = 1; 
     [button addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside]; 
     [cell.contentView addSubView:button atIndex:0]; 
    } 
} 

Вы определили метод myAction:? Если нет, это может привести к сбою вашего приложения.

+0

работы perfectt благодаря – stackiphone

+0

:) рад помочь. – Alok

1

Во-первых, это очень легко:

Добавить подклассом UITableViewCell к вашему проекту, вставить заголовок и добавить ячейку в методе делегата следующим образом:

static NSString *CellIdentifier = @"SpecialCell"; 
// static NSUInteger nTag = 100; 
YourTableViewCellClass *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (specialCell == nil) { 
    specialCell = [[[YourTableViewCellClass alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; 
} 

В вашей новой собственной ячейки класс добавить свои кнопки и взгляды, как вам нравится с

[self addSubview:button]; 

Это ваша особая клетка, клетка для 2-я, 3-я и 4-й ячейки в первой секции.

Как и вы, инициализируйте стандартную ячейку так же, как указано выше. Сейчас здесь идет магия:

if(indexPath.section == 0){ 
    if(indexPath.row == 1||indexPath.row == 2||indexPath.row == 3){ 
     //add text to buttons of your specialCell 
     //add color... 
     return specialCell; 
    } else { 
     return cell; 
    } 
} 

Просто небольшой обзор, как оно должно быть сделано. Надеюсь, что помогает.

+1

дайте мне цыпленок это работает – stackiphone

0
if(indexPath.section == 0) 
{ 
    if(indexPath.row == 1||indexPath.row == 2||indexPath.row == 3) 
    {  

UIButton *deletebtn=[UIButton buttonWithType:UIButtonTypeRoundedRect]; 
      [deletebtn setFrame:CGRectMake(170,5, 25, 25)]; 
      deletebtn.tag=indexPath.row; 
      [deletebtn setImage:[UIImage imageNamed:@"log_delete_touch.png"] forState:UIControlStateNormal]; 
      [deletebtn addTarget:self action:@selector(DeleteRow:) forControlEvents:UIControlEventTouchUpInside]; 
      [cell addSubview:deletebtn]; 
} 
} 
Смежные вопросы