2012-03-14 3 views
6

Я пытаюсь реализовать приложение на основе UITableView. Для этого я выбираю UITableViewStyle - это Group.In мой TableView их раздел, каждый раздел имеет 1 строку.Почему мы проверяем if (cell == nil) в UITableViewController?

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 

    return 1; 
} 
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (indexPath.section==12) 
    { 
     return 120; 
    } 
    else 
    { 
     return 60; 
    } 

} 

Я хочу добавить UITextView на секции

Для этого я сделал следующий код

- (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]; 



    } 
    if ([indexPath section] == 12) 
    { 
     if([indexPath row]==0) 
     { 
      descriptionTextField=[[UITextView alloc] initWithFrame:CGRectMake(5, 8, 290, 106)]; 
      descriptionTextField.font = [UIFont systemFontOfSize:15.0]; 
      descriptionTextField.backgroundColor=[UIColor scrollViewTexturedBackgroundColor]; 

      [descriptionTextField setDelegate:self]; 
      [descriptionTextField setTag:2]; 
      [descriptionTextField setText:@"Enter Location Description."]; 

      descriptionTextField.keyboardType=UIKeyboardTypeDefault; 
      descriptionTextField.returnKeyType=UIReturnKeyNext; 


      descriptionTextField.textColor=[UIColor blackColor]; 
      descriptionTextField.editable=YES; 
      descriptionTextField.autocapitalizationType=UITextAutocapitalizationTypeWords; 
      descriptionTextField.autocorrectionType=UITextAutocorrectionTypeDefault; 
      descriptionTextField.textAlignment=UITextAlignmentLeft; 

      UIToolbar* keboardToolBar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 32)]; 

      UIBarButtonItem *extra=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; 
      UIBarButtonItem *Done=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(keyboardDoneButtonActin:)]; 
      [Done setWidth:65.0f]; 
      [keboardToolBar setItems:[[[NSArray alloc]initWithObjects:extra,Done, nil]autorelease] ]; 
      [extra release]; 
      [Done release]; 

      [keboardToolBar setTintColor:[UIColor blackColor]]; 
      [keboardToolBar setAlpha:.70]; 
      [descriptionTextField setInputAccessoryView:keboardToolBar]; 
      [descriptionTextField setTag:101]; 
      [cell.contentView addSubview:descriptionTextField]; 
      [descriptionTextField release]; 
     } 
    } 

    return cell; 
} 

В initil этапе вид таблицы, как этот

enter image description here

, если я просматриваю таблицу вверх и вниз, тогда раздел uitextView изменился и отобразит несколько мест.

enter image description here

Я не могу понять, моя вина, почему это случилось?

если я реализует приведенный выше код в стороне, если (ячейки == ноль)

- (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]; 

    if ([indexPath section] == 12) 
    { 
     if([indexPath row]==0) 
     { 
      **/* implemention all code here*/** 

      [cell.contentView addSubview:descriptionTextField]; 
      [descriptionTextField release]; 
     } 
    } 

    return cell; 

}

UITextView не Disply, я думаю, что это не распределение.

так, что разница между кодом, реализующего в , если (ячейка == ноль) { внутри }

, если (ячейка == ноль) { } из стороны

+0

разница в том, что когда u написал код внутри ячейки == nil, он будет работать только один раз при запуске, если u выписать сторону, которую он будет создавать каждый раз, когда load load –

+0

Почему значение сечения изменилось при прокрутке таблицы. если я вырву код из стороны? –

+0

еще одна вещь, которую вы можете сделать в своем коде, установить одно значение тега для textview, а затем записать этот код [[cell.contentView viewWithTag: 100 + indexPath.row] removeFromSuperview]; 100 + index.row - значение тега –

ответ

-2
NSString *CellIdentifier = [NSString stringWithFormat:@"%i",indexPath.row]; 

// Dequeue or create a cell of the appropriate type. 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

Это может быть использован вместо

static NSString *CellIdentifier = @"Cell"; 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

это простой пример, чтобы написать внутри клетки == Нилл

- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

static NSString *CellIdentifier = @"CellIdentifier"; 
// Dequeue or create a cell of the appropriate type. 
UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:CellIdentifier]; 
cell= nil; 
if (cell == nil) 
{ 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
    [[cell.contentView viewWithTag:100+indexPath.row] removeFromSuperview]; 

    UIView *selectview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, cell.frame.size.width, 30)]; 
    [selectview setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"strip_s12A-1_h.png"]]]; 
    cell.selectedBackgroundView = selectview; 
    [selectview release]; 

    UILabel *cellTitle=[[UILabel alloc]initWithFrame:CGRectMake(40, 0, 300, 30)]; 
    //cellTitle.adjustsFontSizeToFitWidth=YES; 
    [cellTitle setBackgroundColor:[UIColor clearColor]]; 
    [cellTitle setFont:[UIFont fontWithName:@"Arial Rounded MT Bold" size:17]]; 
    [cellTitle setTextColor:[UIColor blackColor]]; 
    cellTitle.tag = 100+indexPath.row; 

     cellTitle.text= [[[cellArray objectAtIndex:indexPath.section]objectAtIndex:indexPath.row] valueForKey:@"Des2"]; 

    [cell.contentView addSubview:cellTitle]; 

    [cellTitle release]; 
} 
return cell; 
    } 

я думаю, будет достаточно только правый

+0

Возможно ли создать UITextView внутри if (cell == nil) –

+1

проверить приведенный выше код теперь его рабочий штраф тоже –

+0

это работает для u или более необходимо .....? –

3

test if (cell == nil) обрабатывает случай, когда нет повторно используемых ячеек для удаления из очереди, и в этом случае вы должны создать новую ячейку. Когда вы создаете новую ячейку, вы несете ответственность за построение своей иерархии представлений.

+0

, если вы не возражаете, можете усовершенствовать еще немного. –

+2

@MusthafaPP. Ячейки переработаны, а не создаются новые. Причина: производительность, скорость. Чаще всего в [OOP] (https://en.wikipedia.org/wiki/Object-oriented_programming) мы создаем новые экземпляры (объекты) по мере необходимости. Но создание экземпляра нового объекта имеет некоторые накладные расходы, занимает немного времени. В редких случаях, таких как UITableView, нам нужна максимальная производительность. Утилизация существующего объекта при сбросе его ключевых свойств/переменных, подходящих для нового использования, экономит достаточно времени, чтобы гарантировать беспокойство. Итак, если у вас есть доступная ячейка, повторите ее использование. Иначе, создайте новый экземпляр. –

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