通常情况下,一个tableview中,会存在编辑状态,比如说选中几个cell进行删除,或者添加一些section和cell。iOS中自带编辑状态,有删除,插入等,这里就不再叙述了,因为网上面一顿这些个东西。现在,与大家探讨一下,自定的方式来实现cell的选择,能够实现多选,取消选择,在这里我们要进行两级数据的处理,如果一级数据被选择了,二级数据全部被选中,如果一级数据取消选择,二级数据就会取消选择,如果二级数据全被选中,一级数据也就会被选中。那么我们在数据源里面添加一个一级数据被选中的标志位。代码如下:
using System;
using Foundation;
using System.Collections.Generic;
namespace Expland
{
public class Data
{
public Data ()
{
}
//一级标题
public string Title{ get; set;}
//是否展开标志位
public bool ExplandFlag{ get; set;}
//是否选中标志位
public bool SelectedFlag{get;set;}
//二级标题
public List<string> SecondTitle = new List<string> ();
}
}
添加一个全局变量,判断是否进入编辑状态,再添加一个全局变量list集合,存储被选中的路径,代码如下:
using System;
using Foundation;
using System.Collections.Generic;
namespace Expland
{
public class GlobalVariable
{
public GlobalVariable ()
{
}
//编辑状态标志位
public static bool EditFlag{get;set;}
//记录被选中的cell
public static List<NSIndexPath> SelectIndexPath=new List<NSIndexPath>(){};
}
}
这里面的逻辑性比较强,比如说,我们点击一级标题,它的二级标题都会选中,我们应该怎么实现呢?我们是不是应该再GetCell方法里面,首先判断的是不是编辑状态,如果是编辑状态,在判断是不是一级标题选中,如果是的,cell 的图标就是被选中的图标。
using System;
using UIKit;
using Foundation;
using System.Collections.Generic;
using CoreAnimation;
namespace Expland
{
public class MyTableViewSource:UITableViewSource
{
string cellReuseId="cellReuseId";
string headerReuseId="headerReuseId";
List<Data> Title;
//构造函数,传递参数
public MyTableViewSource (List<Data> Title)
{
this.Title = Title;
}
//每一行的内容
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
UITableViewCell cell = tableView.DequeueReusableCell (cellReuseId);
if (cell == null) {
cell = new UITableViewCell (UITableViewCellStyle.Default, cellReuseId);
cell.ImageView.Image = UIImage.FromFile ("unhook");
cell.ImageView.Hidden = true;
cell.SelectionStyle = UITableViewCellSelectionStyle.None;
}
//如果在编辑状态下,显示图片(根据是否被选中)
if (GlobalVariable.EditFlag) {
cell.ImageView.Hidden = false;
//被选中
if (GlobalVariable.SelectIndexPath.FindIndex (v => (v.Row == indexPath.Row && v.Section == indexPath.Secti