如何在tableview中编辑行的文本内容?

时间:2015-04-09 13:43:10

标签: ios objective-c uitableview

我正在使用Xcode 6。

假设我在桌面视图中显示了一个Food对象(每行都是一个属性:名称,卡路里,蛋白质,维生素C,......)。 我想让每一行内容都可以编辑。

一开始,我想到的是,点击“编辑”按钮后,将行内容设为文本字段,但这个解决方案似乎很复杂。

现在,我想到,在选择一行之后,推送一个新的表视图控制器只有一行包含一个标签(属性的名称,例如“卡路里”)和一个包含该值的文本字段。 (事实上​​,我的灵感来自于iPhone / iPod中的设置界面,一般>关于>名称)

1-我可以通过传递属性名称和取决于哪个值来使这个表视图控制器只有一行可重复使用我的Food对象的各种属性(名称,蛋白质,维生素C,....)行被选中了?

2 - 如果是的话,这是一种干净的方式来实现我想做的事情吗?你有其他想法吗?

PS:我应该确切地说我的值可以是字符串(如名称属性)或数字(蛋白质,维生素C,......)。

非常感谢

enter image description here

2 个答案:

答案 0 :(得分:3)

我将向您展示我在其中一个应用中所做的工作。我们有一个配置文件部分waht是一个tableViewController,它有很多用于用户配置文件数据的单元格。如果用户想要编辑这些值,他或她必须单击该单元格,我们将向他/她显示带有输入文本的警报以指定新值。

例如,如果您想在我们的应用中修改您的说明:

enter image description here

enter image description here

所以你需要实现这些。

用于存储您要编辑的单元格的一些变量

@interface MyViewController (){

    //...

    NSString *actionSheetType; // to store what alert I have to show

    NSString *description; // In my example, to store my user desription

    //...
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath捕获单击的单元格

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 1) {
        //...

    } else if (indexPath.row == 2) {
        //...

    } else if (indexPath.row == 3) {
        //...

    } else if (indexPath.row == 4) {

        // Description

        actionSheetType = @"description"; // Set the type

        // Show the alert
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Edit description", nil) message:[[NSUserDefaults standardUserDefaults] stringForKey:USER_DESCRIPTION] delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Ok", nil), nil];
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        [alert show];
    } 

}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex获取新值

- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    // Check what alert have you shown
    if ([actionSheetType isEqualToString:@"password"]){

    } else if ([actionSheetType isEqualToString:@"location"]){

    } else if ([actionSheetType isEqualToString:@"description"]){
        if (buttonIndex == 1) // if click on my alert button
        {
            // Edit my description
            description = [alertView textFieldAtIndex:0].text;
            // Any more actions you will need to do. For example, if you modify a cell or a table alement, reload the table
        }
    } else if ([actionSheetType isEqualToString:@"email"]){
        if (buttonIndex == 1)
        {
        }
    }
}

我希望这可以帮到你!如果您有任何疑问,请发表评论,我会尽快回复您:)

答案 1 :(得分:1)

我认为您的解决方案最好通过UITableViewCell类来处理,该类具有用于开始编辑单元格内容的控制方法。 A Closer Look at Table View Cells