您的位置:首页 > 产品设计 > UI/UE

UITableView,根据indexPath设置cell的编辑样式,删除cell ,增加cell &搜索条

2014-12-09 17:40 567 查看
self.navigationItem.leftBarButtonItem =self.editButtonItem;

//自己创建ButtonItem实现编辑逻辑

UIBarButtonItem *right = [[UIBarButtonItemalloc]
initWithTitle:@"自定义"style:UIBarButtonItemStylePlaintarget:selfaction:@selector(customEditMethod)];

self.navigationItem.rightBarButtonItem = right;

- (void)customEditMethod{

_isEditing = !_isEditing;

[_tableView
setEditing:_isEditinganimated:YES];
}

//系统自带的编辑按钮触发的方法
- (void)setEditing:(BOOL)editing animated:(BOOL)animated{
[supersetEditing:editing
animated:animated];//否则editing值,无法变更

//UITableView,通过此方法,设置编辑状态

[_tableView
setEditing:editing animated:YES];
}

//根据indexPath设置cell的编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath
*)indexPath{

if (indexPath.section == 0) {

returnUITableViewCellEditingStyleDelete;
}else{

returnUITableViewCellEditingStyleInsert;
}
}

//对数据源和cell的操作在此方法中实现
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath{

if (editingStyle ==UITableViewCellEditingStyleDelete) {

//cell处于删除模式

//1、删除数据源中对应的数据 2、tableView删除对应indexPath下的cell

NSMutableArray *array = [_dataArrayobjectAtIndex:indexPath.section];
[array
removeObjectAtIndex:indexPath.row];

//deleteRowsAtIndexPaths:NSArray中存放NSIndexPath对象,tableView会根据数组中的indexPath,删除cell

[tableView deleteRowsAtIndexPaths:[NSArrayarrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];

}elseif (editingStyle ==UITableViewCellEditingStyleInsert){

//cell处于插入模式

StudentModel *model = [[StudentModelalloc]
init];
model.studentName =@"新同学";
model.studentAge = 20;

NSMutableArray *array = [_dataArrayobjectAtIndex:indexPath.section];
[array
insertObject:model atIndex:indexPath.row];
[model
release];

// [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

//表格视图的刷新方法,执行此方法后,tableView会重新调用delegate和dataSource方法
[tableViewreloadData];
}
}

// 增加搜索条

//普通的视图控件(搜索条)

_searchBar = [[UISearchBar
alloc] initWithFrame:CGRectMake(0,0,320,44)];

_tableView = [[UITableView
alloc] initWithFrame:CGRectMake(0,0,320,416)
style:UITableViewStylePlain];

_tableView.delegate =
self;

_tableView.dataSource =
self;

//设置tableView的头视图为搜索条

_tableView.tableHeaderView =
_searchBar;

[self.view
addSubview:_tableView];

//initWithSearchBar
搜索控制器使用的搜索条

//contentsController
搜索控制器开启搜索模式和搜索结果的呈现作用在contentsController上

_displayController = [[UISearchDisplayController
alloc] initWithSearchBar:_searchBar
contentsController:self];

//带有一个searchResultsTableView

_displayController.searchResultsDelegate =
self;

//设置searchResultsTableView的数据源

_displayController.searchResultsDataSource =
self;

//此时程序中有两个tableView,delegate,dataSource均为RootViewController的对象
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: