1. IBAction 함수로 넘기는 sender의 point를 통해서 알아내는 방법
TableViewController에 IBAction함수를 정의하고, Cell에 있는 Button에서 Touch Up inside 이벤트에 대해서 TabelViewController의 아래 함수로 연결을 합니다.그러면, 특정 Cell에서 버튼이 클릭이 되면, 그 버튼객체를 sender로 해서 아래 함수가 호출이 됩니다.
source code
- (IBAction) btnClicked:(id)sender
{
// (1)
CGPoint buttonPoint = [sender convertPoint:CGPointZero toView:self.tableView];
// 2.
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPoint];
if (indexPath != nil) {
//Found Cell
}
}
(1) Cell 내에 있는 Button을 sender로 받고, 그 sender의 위치 포인트를 알아냅니다.- (CGPoint) convertPoint:(CGPoint)point toView:(UIView *)view
: 자신의 좌표 체계에 있는 point 지점을 view의 좌표 체계에서 어느 지점인지 변환함.
즉, Cell 내에 있는 Button의 특정 지점(0,0)을 TableView에서 어느 지점 인지 변환해서 TableView에서의 좌표로 변환을 합니다.
(2) 그리고, 그 포인트에 해당하는 IndextPath를 찾기 위해서, UITableView의 - indexPathForRowAtPoint를 사용해서, 현재 포인트에 해당하는 indexPath를 구할 수 있습니다.
2. Cell 을 통해서 알아내는 방법
TableView의 함수 중에서 - indexPathForCell:(UITableCell*)를 이용할 수 도 있습니다.IBAction이벤트를 받은 함수에서 UITableCell을 가져올 수 있다면, 바로 indexPath를 찾을 수 있을 것입니다.
하지만, 상위 View에서 UITableViewCell을 찾아서 이용해야 합니다.
source code
- (IBAction) btnClicked:(id)sender
{
NSLog(@"btnClicked : %@", sender);
UIView *myView = sender;
UIView *superView = [myView superview];
while (superView != nil && ![superView isKindOfClass:[DBUTableViewCell class]]) {
myView = superView;
superView = [myView superview];
}
if (superView != nil) {
//찾았다.
NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell*)superView];
if (indexPath != nil) {
//이제 찾았다.
[_items removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
}
위와 같이 받은 sender를 통해서 상위에 있는 UITableViewCell을 찾고, TableView의 indexPathForCell을 이용해서 알아 낼 수 있습니다.
그러나, iOS6과 iOS7에서 TableViewCell의 구조가 조금 바뀌었기 때문에 달라질 수 있습니다.
참고하시기 바랍니다.
[참조]
http://code.tutsplus.com/tutorials/blocks-and-table-view-cells-on-ios--mobile-22982
0 comments:
댓글 쓰기