programing

cellForRowAtIndexPath는 어떻게 작동합니까?

luckcodes 2021. 1. 17. 11:30

cellForRowAtIndexPath는 어떻게 작동합니까?


나는 사과 문서를 읽었으며 Objective-C와 같은 초보자에게는 이해할 수 없습니다 . UITableView링크 예제에 따라 여러 열을 구현하려고하는데 작동하지 않으므로 작동 방식을 이해해야합니다 cellForRowAtIndexPath. 개인적으로이 방법은 매우 복잡해 보입니다.

1) 무엇을 반환합니까? UITableViewCell? 그런데 왜 그렇게 이상하게 보일까요?

-(UITableViewCell *)tableView:(UITableView *)tableView 
  • 그게 뭐야? 설명해 주시겠습니까?

2) 어떻게 호출되고 더 중요한 것은 무엇 UITableView입니까? 어떻게 내가이있는 경우를 UITableView'라는 이름 s의 firstTableViewsecondTableView와 나는 그들 (수행하는 다른되고 싶어 cellForRowAtIndexPath다르게)? 어떻게 연결하기로하고 UITableViews이에

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

이 메서드는 허용 NSIndexPath하지 않습니다 UITableView. 내가 뭘 할 건데?


1)이 함수는 테이블보기에 대한 셀을 반환합니다. yes? 따라서 반환 된 객체는 유형 UITableViewCell입니다. 테이블의 행에 표시되는 개체입니다. 이 함수는 기본적으로 테이블 뷰에 대해 셀을 반환합니다. 그러나 두 번째 질문에서 답한 행에 대해 어떤 셀을 반환할지 함수가 어떻게 알 수 있는지 물어볼 수 있습니다.

2) NSIndexPath본질적으로 두 가지입니다.

  • 귀하의 섹션
  • 당신의 행

테이블이 여러 섹션으로 나뉘고 각 섹션에는 고유 한 행이 NSIndexPath있을 수 있으므로 이는 정확히 어떤 섹션과 어떤 행을 식별하는 데 도움 됩니다. 둘 다 정수입니다. 초보자라면 한 섹션으로 만 시도해 보겠습니다.

UITableViewDataSource뷰 컨트롤러에서 프로토콜 을 구현하면 호출됩니다 . 더 간단한 방법은 UITableViewController클래스 를 추가하는 것 입니다. Apple에는 테이블을 설명 할 수있는 함수를 쉽게 구현할 수 있도록 작성된 일부 코드가 있으므로 강력하게 권장합니다. 어쨌든이 프로토콜을 직접 구현하기로 선택한 경우 UITableViewCell개체 를 만들고 어떤 행에 대해서도 반환해야합니다. 테이블보기에 표시되는 셀이 반복해서 재사용되기 때문에 재사용 가능성을 이해하기 위해 클래스 참조를 살펴보십시오 (이것은 매우 효율적인 설계 btw입니다).

두 개의 테이블 뷰가있는 경우 방법을 살펴보십시오. 테이블 뷰가 전달되므로 이에 대해 문제가 없어야합니다.


나는 그것을 분해하려고 노력할 것입니다 ( 문서의)

/* 
 *   The cellForRowAtIndexPath takes for argument the tableView (so if the same object
 *   is delegate for several tableViews it can identify which one is asking for a cell),
 *   and an indexPath which determines which row and section the cell is returned for. 
 */ 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    /*
     *   This is an important bit, it asks the table view if it has any available cells
     *   already created which it is not using (if they are offScreen), so that it can
     *   reuse them (saving the time of alloc/init/load from xib a new cell ).
     *   The identifier is there to differentiate between different types of cells
     *   (you can display different types of cells in the same table view)
     */

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];

    /*
     *   If the cell is nil it means no cell was available for reuse and that we should
     *   create a new one.
     */
    if (cell == nil) {

        /* 
         *   Actually create a new cell (with an identifier so that it can be dequeued). 
         */

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;

    }

    /*
     *   Now that we have a cell we can configure it to display the data corresponding to
     *   this row/section
     */

    NSDictionary *item = (NSDictionary *)[self.content objectAtIndex:indexPath.row];
    cell.textLabel.text = [item objectForKey:@"mainTitleKey"];
    cell.detailTextLabel.text = [item objectForKey:@"secondaryTitleKey"];
    NSString *path = [[NSBundle mainBundle] pathForResource:[item objectForKey:@"imageKey"] ofType:@"png"];
    UIImage *theImage = [UIImage imageWithContentsOfFile:path];
    cell.imageView.image = theImage;

    /* Now that the cell is configured we return it to the table view so that it can display it */

    return cell;

}

This is a DataSource method so it will be called on whichever object has declared itself as the DataSource of the UITableView. It is called when the table view actually needs to display the cell onscreen, based on the number of rows and sections (which you specify in other DataSource methods).


Basically it's designing your cell, The cellforrowatindexpath is called for each cell and the cell number is found by indexpath.row and section number by indexpath.section . Here you can use a label, button or textfied image anything that you want which are updated for all rows in the table. Answer for second question In cell for row at index path use an if statement

In Objective C

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

 NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

  if(tableView == firstTableView)
  {
      //code for first table view 
      [cell.contentView addSubview: someView];
  }

  if(tableview == secondTableView)
  {
      //code for secondTableView 
      [cell.contentView addSubview: someView];
  }
  return cell;
}

In Swift 3.0

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{
  let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!

  if(tableView == firstTableView)   {
     //code for first table view 
  }

  if(tableview == secondTableView)      {
     //code for secondTableView 
  }

  return cell
}

ReferenceURL : https://stackoverflow.com/questions/8079471/how-does-cellforrowatindexpath-work