天天看點

ios開發筆記之tableView自動滾動到已選中項

  我有一個下拉選擇框,裡面是一個tableView,想實作的功能是點選打開下拉菜單後,在前一次的選中項後加一個checkMark,并且讓這一項顯示在tableView中央。

  可以使用tableView的scrollToRowAtIndexPath方法來滾動到指定的IndexPath,但由于tableViewCell的重用機制,當IndexPath所指向的Cell未被加載時,這個方法是無效的,我的解決方案是在viewDidLoad裡周遊所有Cell,代碼如下:

- (void)ScrollToMarkedIndexPath {
    for (NSInteger i = 0; i < self.keyValueDicArray.count; i++) {
        [self tableView:_myTabelView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
    }
    //keyValueDicArray.count是這個tableView中Cell的總數;    
    //因為資料不大,是以我直接用的for循環周遊
    if (_markedIndexPath)
        [_myTabelView scrollToRowAtIndexPath:_markedIndexPath 
                            atScrollPosition:UITableViewScrollPositionMiddle 
                                    animated:NO];
    //_markedIndexPath是上一次被選中的Cell在tableView中的路徑
 }
           

繼續閱讀