iOS TableView的單元格實(shí)現(xiàn)單選功能

我最近在做的一個(gè)項(xiàng)目中遇到了單元格單選的功能,當(dāng)時(shí)我的第一想法是在單元格上添加按鈕,通過點(diǎn)擊改變按鈕的背景圖片并記錄最后一次點(diǎn)擊的indexPath,因?yàn)橹暗捻?xiàng)目中遇到過多選的功能,用這種方法出現(xiàn)了復(fù)用的問題,也就是選擇某個(gè)單元格滑動(dòng)表格時(shí)沒點(diǎn)擊的單元格也被選中了,所以當(dāng)時(shí)就很擔(dān)心單選的時(shí)候出現(xiàn)同樣的問題,果不其然,只顯示最后一個(gè)單元格被選中。然后我找到了這種方法,總結(jié)了一下

這個(gè)功能的實(shí)現(xiàn)只需要在兩個(gè)方法中code即可

首選我們公開一個(gè)屬性

@property(nonatomic,strong)NSIndexPath *lastPath;

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

第一步:在cellForRowAtIndexPath:方法中實(shí)現(xiàn)如下代碼

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

NSInteger row = [indexPath row];

NSInteger oldRow = [lastPath row];

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

//這個(gè)是系統(tǒng)中對(duì)勾的那種選擇框

cell.accessoryType = UITableViewCellAccessoryCheckmark;

}else{

cell.accessoryType = UITableViewCellAccessoryNone;

}

}

第二步:在didSelectRowAtIndexPath:中實(shí)現(xiàn)如下代碼

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

//這里最好不要聲明int類型的,個(gè)人建議

NSInteger newRow = [indexPath row];

NSInteger oldRow = (self .lastPath !=nil)?[self .lastPath row]:-1;

if (newRow != oldRow) {

UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];

newCell.accessoryType = UITableViewCellAccessoryCheckmark;

UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:lastPath];

oldCell.accessoryType = UITableViewCellAccessoryNone;

self .lastPath = indexPath;

}

[tableView deselectRowAtIndexPath:indexPath animated:YES];

}

Ok,可以收工了,這樣實(shí)現(xiàn)之后的效果是每次單擊一個(gè)cell會(huì)做一個(gè)選中的標(biāo)志并且托動(dòng)表視圖時(shí)也不會(huì)出現(xiàn)checkmark的復(fù)用

不過,根據(jù)項(xiàng)目需求,可能會(huì)需要定義一個(gè)按鈕,自定義選擇框的圖片,這也很簡單,只需要將上面的代碼改一下就ok了:

在cellForRowAtIndexPath:中如下修改

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

[cell . selectBtn setBackgroundImage:[UIImage imageNamed:@"選中點(diǎn)"] forState:UIControlStateNormal];

}else{

[cell . selectBtn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];

}

在didSelectRowAtIndexPath:中如下修改

if (newRow != oldRow) {

self.cell = [tableView cellForRowAtIndexPath:indexPath];

[self .cell.selectBtn setBackgroundImage:[UIImage imageNamed:@"選中點(diǎn)"] forState:UIControlStateNormal];

self.cell = [tableView cellForRowAtIndexPath:self .lastPath];

[self .cell.selectBtn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];

self .lastPath = indexPath;

}

最后編輯于
?著作權(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),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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