前言:
很多入門不久的程序員或許都會遇到系統自帶的tableview多選時cell選擇時不能選擇自己想要的點擊時的顏色或者圖片,這讓初級開發者們很煩惱。今天,我試着花了幾個小時的時間用了自己的想法,去做了自定義的tableview的多選,僅供參考使用,如有覺得寫的不好的,可以隨時交流,謝謝。
1.自定義cell,假設cell總共有三個控件;
(1)_selecedImgIcon則為設置多選時才出現的我們所想自定義的selected控件,設置這個控件時需要把它設置在視圖左邊,點擊多選時向右推才出現
_selecedImgIcon.frame = CGRectMake(-48 * Scale_width, 56 * Scale_heigh, 46 * Scale_heigh, 46 * Scale_heigh);
_noteImageV.frame = CGRectMake(22 * Scale_width, 38 * Scale_heigh, 82 * Scale_heigh, 82 * Scale_heigh);
_noteTittle.frame = CGRectMake(124 * Scale_width, 42 * Scale_heigh, 200 * SCALEX, 30 * Scale_heigh);
_noteTime.frame = CGRectMake(124 * Scale_width, 96 * Scale_heigh, 200 * SCALEX, 20 * Scale_heigh);
由於cell的contentView是只讀的,不可以改變其frame,因此,需要在contentView上加一個contentV,把所有需要用的控件都放在上面,需要多選時再將contentV向左推,將多選時的控件顯示出來。所以記得selected控件的x一定要置於左端,即x坐標要是負的
2.聲明一個bool屬性的editing,初始時為NO;
BOOL _editing;
_editing = NO;
3.添加一個多選的button,為button添加一個target;
@selector(onMultipleChoice)
4.實現onMultipleChoice這個方法;(記得先設置好未選擇時的圖片)
// 設置多選時contentV的x需要往右移多少才能將cell推出來(自己算)
float contentX = editing ? 70 * Scale_width : 0;
// 獲取所有的cell,並設置動畫效果將cell推出
for (int i = 0; i < _array.count; i ++)
{ // 這里假設只有一個section
NoteTableViewCell *cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
[UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
cell.contentV.frame = CGRectMake(contentX, 0, cell.contentView.frame.size.width, cell.contentView.frame.size.height);
NSLog(@"%f",cell.contentView.center.x);
[cell layoutIfNeeded];
} completion:^(BOOL finished) {
}];
}
5.實現兩個tableview的代理方法:分別為選中時和未選中時;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
/**********
此處寫選中時的數據操作
***********/
if (_editing)
{
_cell = [tableView cellForRowAtIndexPath:indexPath];
_cell.selecedImgIcon.image = [UIImage imageNamed:@"privacy_selected02"];
return;
}
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(3_0)
{
/**********
此處寫未選中時的數據操作
***********/
_cell = [tableView cellForRowAtIndexPath:indexPath];
_cell.selecedImgIcon.image = [UIImage imageNamed:@"privacy_selected01"];
}
6.實現后如圖所示:
7.結語:
希望各位大神們,看了有什么想法或有什么建議的可以跟我聊聊,我相信交流永遠是成長最快的。