프로그래밍 방식으로 테이블 뷰 행 선택


답변:


109

에서 참조 문서 :

이 메서드를 호출해도 대리인이 tableView:willSelectRowAtIndexPath:또는 tableView:didSelectRowAtIndexPath:메시지를 받거나 UITableViewSelectionDidChangeNotification관찰자 에게 알림을 보내지 않습니다 .

내가 할 일은 :

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self doSomethingWithRowAtIndexPath:indexPath];
}

그런 다음 selectRowAtIndexPath를 호출하려는 위치에서 대신 doSomethingWithRowAtIndexPath를 호출하십시오. 또한 UI 피드백이 발생하도록하려면 selectRowAtIndexPath를 추가로 호출 할 수도 있습니다.


4
또는 프로그래밍 방식으로 행을 선택할 때 tableView : didSelectRowAtIndexPath :를 직접 호출 할 수 있습니다 (대리자로 연결 한 클래스에서).
— Kendall Helmstetter Gelner 2019 년

3
이 방법은 나에게 해킹처럼 보입니다. 작업이 완료되었지만 더 나은 방법이 있어야한다고 생각합니다.
— Tapan Thaker

1
"doSomethingWithRowAtIndexPath"호출을 작성해야한다고 생각하지 않습니다. 델리게이트 메소드를 호출하고 델리게이트 메소드를 구현 한 곳에서 didSelect 로직을 실행하는 데 필요한 인수를 전달할 수 없습니까?
— ImpactZero

111

Jaanus가 말한 것처럼 :

이 (-selectRowAtIndexPath : animated : scrollPosition :) 메서드를 호출해도 대리자가 tableView : willSelectRowAtIndexPath : 또는 tableView : didSelectRowAtIndexPath : 메시지를 받거나 UITableViewSelectionDidChangeNotification 알림을 관찰자에게 보내지 않습니다.

따라서 delegate메소드를 직접 호출하면 됩니다.

예를 들면 다음과 같습니다.

스위프트 3 버전 :

let indexPath = IndexPath(row: 0, section: 0);
self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableViewScrollPosition.none)
self.tableView(self.tableView, didSelectRowAt: indexPath)

ObjectiveC 버전 :

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView selectRowAtIndexPath:indexPath 
                            animated:YES 
                      scrollPosition:UITableViewScrollPositionNone];
[self tableView:self.tableView didSelectRowAtIndexPath:indexPath];

스위프트 2.3 버전 :

 let indexPath = NSIndexPath(forRow: 0, inSection: 0);
 self.tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: UITableViewScrollPosition.None)
 self.tableView(self.tableView, didSelectRowAtIndexPath: indexPath)

63

UITableView의 selectRowAtIndexPath : animated : scrollPosition : 트릭을 수행해야합니다.

UITableViewScrollPositionNonescrollPosition을 전달 하면 사용자가 움직임을 볼 수 없습니다.


작업을 수동으로 실행할 수도 있습니다.

[theTableView.delegate tableView:theTableView didSelectRowAtIndexPath:indexPath]

그런 다음 selectRowAtIndexPath:animated:scrollPosition:강조 표시와 관련 논리가 발생합니다.


미안 해요, 내가 사용하는 것입니다. 실수로 scrollToRowAtIndexPath를 넣었습니다. 질문을 업데이트했습니다. scrollToRowAtIndexPath는 셀만 강조 표시합니다.
— 4thSpace

2
네, 죄송합니다 내가 게시 한 문서 링크에서 didSelectRowAtIndexPath를 실행하지 않는다고 말합니다. 읽는 법을 배워야합니다.
— anq

@anq : 대단히 감사합니다! 사용자 정의 셀에서 didSelectRowAtIndexPath : indexPath를 호출하면 도움이됩니다.
— 벤틀리

21

일부 행을 선택하려면 도움이 될 것입니다

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[someTableView selectRowAtIndexPath:indexPath 
                           animated:NO 
                     scrollPosition:UITableViewScrollPositionNone];

이것은 또한 행을 강조 표시합니다. 그런 다음 위임

 [someTableView.delegate someTableView didSelectRowAtIndexPath:indexPath];

18

스위프트 3/4/5 솔루션

행 선택

let indexPath = IndexPath(row: 0, section: 0)
tblView.selectRow(at: indexPath, animated: true, scrollPosition: .bottom)
myTableView.delegate?.tableView!(myTableView, didSelectRowAt: indexPath)

행 선택 해제

let deselectIndexPath = IndexPath(row: 7, section: 0)
tblView.deselectRow(at: deselectIndexPath, animated: true)
tblView.delegate?.tableView!(tblView, didDeselectRowAt: indexPath)

나를 위해 '.delegate?'를 추가하십시오. 열쇠였습니다. (Swift 4.5)
— KoreanXcodeWorker

4

iPad 및 iPhone 플랫폼에는 두 가지 방법이 있으므로 두 가지를 모두 구현해야합니다.

  • 선택 핸들러
  • segue.

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    
    // Selection handler (for horizontal iPad)
    [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
    
    // Segue (for iPhone and vertical iPad)
    [self performSegueWithIdentifier:"showDetail" sender:self];

3

이 범주를 사용하여 테이블 행을 선택하고 지연 후 지정된 segue를 실행하십시오. 메소드
내에서 이것을 호출하십시오 viewDidAppear.

[tableViewController delayedSelection:withSegueIdentifier:]


@implementation UITableViewController (TLUtils)

-(void)delayedSelection:(NSIndexPath *)idxPath withSegueIdentifier:(NSString *)segueID {
    if (!idxPath) idxPath = [NSIndexPath indexPathForRow:0 inSection:0];                                                                                                                                                                 
    [self performSelector:@selector(selectIndexPath:) withObject:@{@"NSIndexPath": idxPath, @"UIStoryboardSegue": segueID } afterDelay:0];                                                                                               
}

-(void)selectIndexPath:(NSDictionary *)args {
    NSIndexPath *idxPath = args[@"NSIndexPath"];                                                                                                                                                                                         
    [self.tableView selectRowAtIndexPath:idxPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];                                                                                                                            

    if ([self.tableView.delegate respondsToSelector:@selector(tableView:didSelectRowAtIndexPath:)])
        [self.tableView.delegate tableView:self.tableView didSelectRowAtIndexPath:idxPath];                                                                                                                                              

    [self performSegueWithIdentifier:args[@"UIStoryboardSegue"] sender:self];                                                                                                                                                            
}

@end

2
질문은 segues와 아무 관련이 없습니다.
— deleted_user

예, 귀하의 답변에 관한 질문과 관련이 없습니다
— dulgan

2
이 답변을 감사하십시오. 사용자가 동일한 동작을 원하지만 스토리 보드를 사용하는 경우 완벽하게 작동합니다.
— Bijoy Thangaraj
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.