先新建一個項目,命名為UITableViewDemo,storyboard中拖入一個UITableViewController,然后新建一個繼承自UITableViewController的類,命名為UDTableViewController。在storyboard中將拖入的UITableViewController的Custom Class,Class設置為剛剛新建的UDTableViewController。
定義一個復用標識
static NSString * const reuseIdentifier = @"UDCell";
當前tableview注冊UITableViewCell類并設置復用標識為上面的標識
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:reuseIdentifier];
// Uncomment the following line to PReserve selection between presentations.
// self.clearsselectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.rightBarButtonItem=self.editButtonItem;
}
采用復用的cell,并設置顯示內容
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return 20;
}
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
UITableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier forIndexPath:indexPath];
cell.textLabel.text= [NSString stringWithFormat:@"%ld", indexPath.row];
// Configure the cell...
returncell;
}
現在看起來是這個樣子:
正常狀態
編輯狀態
現在怎么讓UITableView編輯時為多選呢?
那就是實現UITableView的代理方法
- (UITableViewCellEditingStyle)tableView:(UITableView*)tableView editingStyleForRowAtIndexPath:(NSIndexPath*)indexPath;
UITableViewCellEditingStyle為編輯狀態, 聲明如下:
typedefNS_ENUM(NSInteger, UITableViewCellEditingStyle) {
UITableViewCellEditingStyleNone, //無
UITableViewCellEditingStyleDelete,//刪除狀態
UITableViewCellEditingStyleInsert//插入狀態
};
而多選就是UITableViewCellEditingStyleDelete、UITableViewCellEditingStyleInsert兩者的組合。
所以返回狀態如下:
- (UITableViewCellEditingStyle)tableView:(UITableView*)tableView editingStyleForRowAtIndexPath:(NSIndexPath*)indexPath
{
return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}
現在可以多選了,效果圖:
多選
下面的方法為提交編輯時響應的方法,比如:刪除狀態下點擊cell右邊的刪除按鈕時;插入狀態下點擊左側添加按鈕時。編輯狀態下并不會調用此方法,所以只能取其它的辦法。
- (void)tableView:(UITableView*)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath
怎么保存多選的row呢?
如果要保存多選的row,我有一個方法(如果你有更好的方法,請告訴我
新聞熱點
疑難解答