iOS TableView實現單選checkmark功能


相信大家在做項目時有遇到需要實現這種功能---實現單選某一個cell表示選中

這個功能的實現只需要在兩個方法中code即可

首選我們公開一個屬性 

@property(nonatomic,strong)NSIndexPath *lastPath;並且對其synthesize

主要是用來接收用戶上一次所選的cell的indexpath

第一步:在cellForRowAtIndexPath:方法中實現如下代碼

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

      NSInteger row = [indexPath row];

      NSInteger oldRow = [lastPath row];

       if (row == oldRow && lastPath!=nil) {

        cell.accessoryType = UITableViewCellAccessoryCheckmark;

       }else{

         cell.accessoryType = UITableViewCellAccessoryNone;

    }

}

 

第二步:在didSelectRowAtIndexPath:中實現如下代碼

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

    int newRow = [indexPath row];

    int oldRow = (lastPath !=nil)?[lastPath row]:-1;

    if (newRow != oldRow) {

        UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];

        newCell.accessoryType = UITableViewCellAccessoryCheckmark;

        UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:lastPath];

        oldCell.accessoryType = UITableViewCellAccessoryNone;

        lastPath = indexPath;

     }

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}

 

Ok,可以收工了,這樣實現之后的效果是每次單擊一個cell會做一個選中的標志並且托動表視圖時也不會出現checkmark的復用

希望對初學者有幫助到!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM