2011-02-23 8 views
0

여기에서 모든 예제를 읽은 후 UITableViewCell에 단추를 추가하기 위해 다음 코드를 작성했지만 셀에 표시 할 수 없습니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?UITableViewCell에 UIButton이 표시되지 않습니다.

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

    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease]; 
    } 

UIButton *cellButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
[cellButton setFrame:CGRectMake(0.0f, 5.0f, tableView.frame.size.width-2, 44.0f)]; 
[cellButton setTitle:[aList objectAtIndex:indexPath.row] forState:UIControlStateNormal]; 
[cell.contentView addSubview:cellButton]; 
[cellButton release]; 
return cell; 
} 

감사합니다, 존

당신이 buttonWithType을 통해 생성 한 버튼을 release를 호출 할 필요가 없습니다

답변

6

; release를 호출하면 보유 개수가 떨어지며 원하는 시점 이전에 버튼이 삭제됩니다.

+0

그건 ... 너보다! – user278859

2

두 가지를 잘못하고 있습니다. 첫째, 위의 포스터가 말했듯이, 당신은 버튼을 과도하게 사용하고 있으며, 프로그램은 앞으로 어떤 시점에서 충돌 할 수 있습니다. 일반적으로 정적 메서드는 자동 렌더링 된 객체를 반환하므로 사전에 보유하지 않은 경우 직접 해제 할 필요가 없습니다.

위의 코드는 tablecell을 다시 사용하기 때문에 원하는 동작이 아닌 UIButton을 셀에 여러 번 추가합니다. 테이블 셀이 초기화 될 때 UIButton을 추가하십시오. 또한 버튼 rect가 정상 셀 체크로 테이블 셀 내부에 있는지 확인할 수도 있습니다.

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

    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease]; 

UIButton *cellButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
[cellButton setFrame:CGRectMake(0.0f, 5.0f, tableView.frame.size.width-2, 44.0f)]; 
[cellButton setTitle:[aList objectAtIndex:indexPath.row] forState:UIControlStateNormal];  
[cell addSubview:cellButton]; 
    } 

return cell; 
} 
+0

이것은 매우 도움이되었습니다. 당신보다! – user278859

관련 문제