// 当cell被选中的时候,就会调用
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// 取出数组中对应的model
HeroModel *heroModel = self.dataArray[indexPath.row];
// 弹出提示框
UIAlertView *alertView = [[UIAlertViewalloc]
initWithTitle:@"编辑"
message:nil
delegate:self
cancelButtonTitle:@"取消"
otherButtonTitles:@"确定",nil];
// 显示输入框
/**
UIAlertViewStyleDefault = 0,
UIAlertViewStyleSecureTextInput,
UIAlertViewStylePlainTextInput,
UIAlertViewStyleLoginAndPasswordInput
*/
alertView.alertViewStyle =UIAlertViewStylePlainTextInput;
// 把英雄的名字赋值给 alertView中textField
// 取出aletView的 textField
UITextField *textField = [alertView textFieldAtIndex:0];
textField.text = heroModel.name;
// 点击cell的时候,把row设置给alertView的tag属性
alertView.tag = indexPath.row;
// 展示alertView
[alertView show];
}
#pragma mark -
#pragma mark - alertView的代理方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1) { // 点击了确定按钮
/**
修改数据显示,修改英雄的名字
*/
// 取出 alertView中的文本输入框
UITextField *textField = [alertView textFieldAtIndex:0];
// 修改过之后的名字
NSString *newName = textField.text;
// 修改数据源中 的英雄名字
// 取出alertView 的tag ,点击的某个行
NSInteger index = alertView.tag;
// 取出点击行所对应的数据源中的模型
HeroModel *model = self.dataArray[index];
// 修改model中的 name属性
model.name = newName;
// 刷新tableView中的数据,对所有数据进行刷新
// [_tableView reloadData];
// // 对某一行cell的数据进行刷新
NSIndexPath *indexPath=[NSIndexPath indexPathForRow:indexinSection:0];
[_tableViewreloadRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationLeft];
}
}
======================================
// 编辑cell的标题以及UIAlertController的使用
//当cell 被选中的时候, 就会调用
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
// 弹出alertController
UIAlertController *controller = [UIAlertControlleralertControllerWithTitle:@"编辑"message:nilpreferredStyle:UIAlertControllerStyleAlert];
// 添加action-动作(按钮)
UIAlertAction *cancelAction = [UIAlertActionactionWithTitle:@"取消"style:UIAlertActionStyleCancelhandler:nil];
// 添加到 alerController
[controller addAction:cancelAction];
// 添加确定按钮,点击确定按钮会执行block中的代码
UIAlertAction *sureAction = [UIAlertActionactionWithTitle:@"确定"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction *_Nonnull action) {
// 1. 取出新的英雄名字
// 1.1 取出alertController中 textField
UITextField *textField = [controller textFields][0];
NSString *newName = textField.text;
// 2. 修改模型中的数据
HeroModel *heroModel = self.dataArray[indexPath.row];
heroModel.name = newName;
// 3. 刷新数据源
// [_tableView reloadData];
[_tableViewreloadRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationLeft];
}];
// 取出点击cell对应的模型
HeroModel *heroModel = self.dataArray[indexPath.row];
// 添加输入框
[controller addTextFieldWithConfigurationHandler:^(UITextField *_NonnulltextField) {
// 给textField 设置文本
textField.text = heroModel.name;
}];
// 添加确定按钮到 alertController
[controller addAction:sureAction];
[selfpresentViewController:controller animated:YEScompletion:nil];
}