@interface SmartHome_MainViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutletUITableView *MainTableView;
@property(strong,nonatomic)NSMutableArray *RoomNames;
直接上代码,实现tableview的方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [self.RoomNamescount];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier =@"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCellalloc] initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.textLabel.text = [self.RoomNamesobjectAtIndex:indexPath.row];
cell.selectionStyle =UITableViewCellSelectionStyleNone;
return cell;
}
//以下是添加删除功能的代码
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle ==UITableViewCellEditingStyleDelete) {
[self.RoomNames removeObjectAtIndex:indexPath.row]; // Delete the row from the data source.
[self.MainTableView deleteRowsAtIndexPaths:[NSArrayarrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
//如果删除section调用上面的方法会崩溃,因为删除了某个section的某一个row,但是section却没有被删除,系统就会发生UI崩溃。
[tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];
}
elseif (editingStyle ==UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}