iOS tableView的點(diǎn)擊聯(lián)動(dòng)效果

效果是這樣子的:如下圖
1

639F260E-22C5-44CB-BA80-E17EF395BFAC.png

導(dǎo)航欄上有兩個(gè)按鈕 點(diǎn)擊時(shí)切換當(dāng)前界面,當(dāng)前的界面其實(shí)是一個(gè)tableview的cell,點(diǎn)擊下一頁(yè)或者上一頁(yè)的時(shí)候tableview會(huì)上下翻頁(yè),就是這么個(gè)效果。
2

E8F76E55-A832-4D86-AE54-5BBF66DCC594.png

當(dāng)翻到最后一頁(yè)或者第一頁(yè)時(shí),按鈕不可用

下面是主要的代碼:

聲明全局變量  NSInteger _currentIndex;//當(dāng)前的索引值

tableview的上下翻頁(yè)效果:_tableView.pagingEnabled = YES; 為了美觀去掉豎直方向滾動(dòng)的滑條:_tableView.showsVerticalScrollIndicator = NO;

處理點(diǎn)擊事件:
#pragma mark - 按鈕點(diǎn)擊事件
- (void)frontClick {
    /**< 上一條消息 */
    _nextBtn.enabled = YES;
    _currentIndex--;     //判斷有沒(méi)有上一條
    NSLog(@"currentIndex:%ld", (long)_currentIndex);
    if (_currentIndex >=  0) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_currentIndex inSection:0];
        [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    } else {
        _currentIndex = 0;
        _frontBtn.enabled = NO;
    }
    
}

- (void)nextClick {
    /**< 下一條消息 */
    _frontBtn.enabled = YES;
    _currentIndex ++;       //判斷有沒(méi)有下一條
    NSLog(@"currentIndex:%ld", (long)_currentIndex);
    if (_currentIndex< _arr.count) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_currentIndex inSection:0];
        [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    }    else {
        _nextBtn.enabled = NO;
        _currentIndex = _arr.count - 1;
    }
    
}

小結(jié):其實(shí)主要的就是
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_currentIndex inSection:0];
        [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];

通過(guò)_currentIndex 找到當(dāng)前的索引,然后讓tableview滾動(dòng)到指定的索引行數(shù)。
還有一點(diǎn)小邏輯的操作,就是點(diǎn)擊按鈕時(shí)的_currentIndex的變化。首先_currentIndex默認(rèn)為0,那么當(dāng)開(kāi)始點(diǎn)擊上一條的時(shí)候,此時(shí)用_currentIndex-- 判斷當(dāng)前的索引有沒(méi)有上一條,如果_currentIndex >= 0的話就讓tableview向指定的索引滾動(dòng)。如果<0 了 就讓_currentIndex = 0;使按鈕失效。然后當(dāng)點(diǎn)擊下一條按鈕的時(shí)候,讓_currentIndex ++ 判斷當(dāng)前所以是不是超出了數(shù)組中的元素的索引,如果沒(méi)有就滾動(dòng)。如果超出了 就讓_currentIndex為數(shù)組里元素的最后的索引值。讓按鈕失效。大體就這樣子。

代碼gitHub地址:https://github.com/irembeu/TableViewRepository.git

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容