2009-05-30 1 views
8

나는 사용자 정의 cell.the tableview 테이블을 가지고 많은 섹션과 rows.i 셀에 사용자 지정 단추가 있습니다. 이제 버튼을 클릭하면 섹션 번호와 행 번호를 얻고 싶습니다.? 올바른 내 int section = indexPath.section;섹션 번호 및 행 번호를 사용자 정의 셀 버튼 클릭 하시겠습니까?

는 행 번호에 액세스 할 수 (:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 

는 섹션 번호에 액세스하려면 : 당신이 당신의있는 tableView에서 셀을 선택하면 다음과 같은 메서드가 호출이

답변

26

UIControl 이벤트 처리 메서드를보기 컨트롤러에 구현하고 에 대한 처리기로 모두 단추를 설정해야합니다.

[theCell.button addTarget: self 
        action: @selector(buttonPressed:withEvent:) 
     forControlEvents: UIControlEventTouchUpInside]; 

그런 다음 이벤트 핸들러는 다음과 같이 보일 것이다 : 당신의 -tableView:cellForRowAtIndexPath: 함수 내에서 당신은 같은 일을 할 것, 즉 사용자가 행의 버튼을 탭하면 호출되지 않습니다

- (void) buttonPressed: (id) sender withEvent: (UIEvent *) event 
{ 
    UITouch * touch = [[event touches] anyObject]; 
    CGPoint location = [touch locationInView: self.tableView]; 
    NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint: location]; 

    /* indexPath contains the index of the row containing the button */ 
    /* do whatever it is you need to do with the row data now */ 
} 
+6

약간의 수정 ... [이벤트 터치] [이벤트 allTouches] – dizy

+0

위대한되어야합니다! 이게 정확히 내가 찾고있는 ... 감사합니다 .. – mshsayem

6

에 대한 어떤 생각 섹션) : int row = indexPath.row;

+2

; 행 배경 자체를 탭하는 경우에만 호출됩니다. –

8

몇 가지 생각 :

당신이있는 UITableViewCell을 찾을 때까지 당신은 버튼의 수퍼 계층 구조를 통해 반복 할 수 후 전화 - (NSIndexPath *) indexPathForCell : jQuery과에 (있는 UITableViewCell *) 세포.

- (void)buttonClicked:(id)sender { 
    UIView *button = sender; 

    for (UIView *parent = [button superview]; parent != nil; parent = [parent superview]) { 
    if ([parent isKindOfClass: [UITableViewCell class]]) { 
     UITableViewCell *cell = (UITableViewCell *) parent;   
     NSIndexPath *path = [self.tableView indexPathForCell: cell]; 

     // now use the index path 

     break; // for 
    } 
    } 
} 

단추를 사용하여 행을 참조하는 인덱스를 저장할 수 있습니다. 이것은 단 하나의 정수만 가지고 있기 때문에 하나의 섹션을 가지고 있거나 행을 평면 목록으로 관리 할 때 가장 합리적입니다.

UITableViewCell을 하위 클래스로 캡슐화하여 단추를 캡슐화 할 수 있습니다. UITableViewCell은 버튼 이벤트에 응답하고 자신을 전달하는 자체 대리자에게 이벤트를 재방송 할 수 있습니다. 이벤트 대리자는 UITableView에서 - (NSIndexPath *) indexPathForCell : (UITableViewCell *) 셀을 호출하여 인덱스 경로를 가져올 수 있습니다. 당신의있는 UITableViewCell subclassTo의 인스턴스 변수는 셀의 인덱스 경로를 저장할 수 있습니다

1

추가 :

NSIndexPath *myIndexPath; 

당신이 셀 만들 때 : 새로 생성에 indexpath에

cellForIndexPath: 

패스를/재활용 된 셀.

이제 버튼을 누르면 셀의 ivar에서 색인 경로를 읽습니다.

관련 문제