2010-12-19 15 views
11

por favor alguien puede mostrar un ejemplo de la edición in situ de células UITableView ... Soy consciente de UITableView métodos de delegado como cellForRowAtIndexPath, etc ...La edición directa de células UITableView

Pero no lo hago saber cómo permitir la edición de texto en el lugar de la celda?
También se puede utilizar este valor con Core Data, es decir, puede persistir ...

Lo que estoy buscando se puede ver en Configuración -> Wi-Fi, donde se ven los campos Dominio, Cliente, IP , etc. donde los valores se pueden establecer en el mismo lugar.

Además, ¿hay alguna desventaja de usar Vs de edición in situ que tengan un controlador de vista separado para controlar un valor de campo?

Respuesta

18

Agregue UITextField a su celular.

De cualquier forma que elija editar una entrada, ya sea que use CoreData, o lo que sea para almacenar la información, de alguna manera necesita guardarla. Si utiliza el método de edición en la Tabla, puede usar los delegados textField para guardar los datos a medida que el usuario acceda a return.

En su cellForRowAtIndexPath:

myTextField = [[UITextField alloc] initWithFrame:CGRectMake(0,10,125,25)]; 
myTextField.adjustsFontSizeToFitWidth = NO; 
myTextField.backgroundColor = [UIColor clearColor]; 
myTextField.autocorrectionType = UITextAutocorrectionTypeNo; 
myTextField.autocapitalizationType = UITextAutocapitalizationTypeWords; 
myTextField.textAlignment = UITextAlignmentRight; 
myTextField.keyboardType = UIKeyboardTypeDefault; 
myTextField.returnKeyType = UIReturnKeyDone; 
myTextField.clearButtonMode = UITextFieldViewModeNever; 
myTextField.delegate = self; 
cell.accessoryView = myTextField; 

TextField Delegates:

- (BOOL)textFieldShouldReturn:(UITextField *)textField { 
    if(textField == myTextField){ 
     /* do your saving here */ 
    } 
} 
+0

Si bien parece que lo tienes justo justo en lo que yo estoy buscando, todavía tenía algunas preguntas como cuál debe ser el estilo de celda de la tabla (como Val1, Val2, etc.) ¿Es accesorioView el mismo que accesorioTipo? También se puede utilizar este método solo para la edición de texto in situ o ¿puedo usarlo para editar otros tipos como decir una fecha? – hmthur

+0

El estilo predeterminado está bien, ya que no tendrá ningún detalleTexto. AccessoryView se puede utilizar para replicar el tipo de acessory, por lo que en lugar de un botón Disclusre, puede reemplazarlo con un TextField. Entonces no necesitarás un accesorio tipo. Puede usar este método para editar Fechas, Números, texto, cualquier cosa que pueda pensar. – WrightsCS

0

Esto es muy antigua .. y probablemente necesita una respuesta más reciente .. Sólo tenía este problema y hackeado algo .. tal vez alguien lo encuentre útil ..

Creé un Table View Controller que agrega un cuadro de mensaje agrega el final de una "lista de elementos" que está almacenada en NSUserDefau lts ... Referencia

// 
    // MyItemListTVC.m 
    // Best10 
    // 
    // Created by Francois Chaubard on 12/26/13. 
    // Copyright (c) 2013 Chaubard. All rights reserved. 
    // 

    #import "MyItemListTVC.h" 
    #import "AppDelegate.h" 

    @interface MyItemListTVC() 

    @property (strong, nonatomic) UIRefreshControl IBOutlet  *refreshControl; 
    @property (strong,nonatomic) UIBarButtonItem *addButton; 
    @property (strong,nonatomic) UITextView *messageBox; 

    @end 

    @implementation MyItemListTVC 


    @synthesize refreshControl; 
    @synthesize itemList; 

    - (id)initWithStyle:(UITableViewStyle)style 
    { 
     self = [super initWithStyle:style]; 
     if (self) { 
      // Custom initialization 
     } 
     return self; 
    } 

    - (void)viewDidLoad 
    { 
     [super viewDidLoad]; 
     self.itemList=[(AppDelegate *)[UIApplication sharedApplication].delegate getitems]; 

     // 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; 
     // Do any additional setup after loading the view, typically from a nib. 
     self.navigationItem.leftBarButtonItem = self.editButtonItem; 

     self.addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject:)]; 

     self.addButton.enabled = false; 

     //UIBarButtonItem *saveButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(save:)]; 
     [self.navigationItem setRightBarButtonItems:@[self.addButton] animated:YES]; 
    } 



    - (void)didReceiveMemoryWarning 
    { 
     [super didReceiveMemoryWarning]; 
     // Dispose of any resources that can be recreated. 
    } 

    - (void)insertNewObject:(id)__unused sender 
    { 

     NSMutableArray *temp = [[NSMutableArray alloc] initWithArray:self.itemList]; 

     self.itemList = nil; 
     [self.tableView reloadData]; 

     [temp addObject:self.messageBox.text]; 
     [[NSUserDefaults standardUserDefaults] setObject:temp forKey:@"items"]; 
     self.itemList=[(AppDelegate *)[UIApplication sharedApplication].delegate getitems]; 
     self.messageBox = nil; 
     self.addButton.enabled = NO; 
     [self.tableView reloadData]; 

     [self.tableView setNeedsDisplay]; 
     [CATransaction flush]; 
    } 

    - (void) save:(id)__unused sender { 


    } 



    #pragma mark - Table View 


    - (NSInteger)tableView:(UITableView *)__unused tableView numberOfRowsInSection:(NSInteger)section 
    { 

     return [self.itemList count]+1; 
    } 

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
     UITableViewCell *cell; 
     if (indexPath.row ==[self.itemList count] ) { 
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MessageBox Cell"]; 

      UITextView *messageBox= [[UITextView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, 100)]; 

      cell.userInteractionEnabled=YES; 
      messageBox.delegate=self; 
      [messageBox setEditable:YES]; 
      [messageBox setUserInteractionEnabled:YES]; 
      messageBox.editable=YES; 
      messageBox.font = cell.textLabel.font; 
      messageBox.textAlignment = NSTextAlignmentCenter; 
      messageBox.textColor = [UIColor grayColor]; 
      messageBox.text = @"insert new activity"; 
      self.messageBox = messageBox; 
      [cell addSubview: messageBox]; 
     }else{ 
      cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; 

      [self configureCell:cell atIndexPath:indexPath]; 
     } 
     return cell; 
    } 

    - (BOOL)tableView:(UITableView *)__unused tableView canEditRowAtIndexPath:(NSIndexPath *)__unused indexPath 
    { 
     // Return NO if you do not want the specified item to be editable. 
     return YES; 
    } 

    - (void)tableView:(UITableView *)__unused tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
     if ((editingStyle == UITableViewCellEditingStyleDelete)&&([self.itemList count]>indexPath.row)) { 

      NSMutableArray *temp = [[NSMutableArray alloc] initWithArray:self.itemList]; 
      [temp removeObjectAtIndex:indexPath.row]; 
      [[NSUserDefaults standardUserDefaults] setObject:temp forKey:@"items"]; 
      self.itemList=[(AppDelegate *)[UIApplication sharedApplication].delegate getitems]; 
      [self resignFirstResponder]; 

      [self.tableView reloadData]; 
     } 
    } 

    - (BOOL)tableView:(UITableView *)__unused tableView canMoveRowAtIndexPath:(NSIndexPath *)__unused indexPath 
    { 
     // The table view should not be re-orderable. 
     return YES; 
    } 




    - (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath 
    { 
     if ([self.itemList count] > 0){ 

      cell.textLabel.text = [self.itemList objectAtIndex:indexPath.row]; 

     } 
    } 

    #pragma mark - UITextViewDelegate 
    - (void)textViewDidBeginEditing:(UITextView *)textView { 

     textView.text = @"-ing"; 
     [self.messageBox setSelectedTextRange:[self.messageBox textRangeFromPosition:[self.messageBox positionFromPosition:self.messageBox.beginningOfDocument offset:1] toPosition:self.messageBox.beginningOfDocument]]; 


    } 
    -(void)textViewDidChange:(UITextView *)textView 
    { 
     if (textView.text.length > 4) { 
      self.addButton.enabled=YES; 
     }else{ 
      self.addButton.enabled=NO; 
     } 
    } 

    - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
     if ((indexPath.row ==[self.itemList count])) { 
      return UITableViewCellEditingStyleNone; 
     }else{ 
      return UITableViewCellEditingStyleDelete; 
     } 
    } 

    - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { 
     if ([text isEqualToString:@"\n"]) { 

      if (textView.text.length > 4) { 
       [self insertNewObject:textView.text]; 
      } 
      [self resignFirstResponder]; 
      return NO; // or true, whetever you's like 

     }else if((textView.text.length-range.location)<4){ 
      return NO; 
     } 

     if (textView.text.length > 4) { 
      self.addButton.enabled=YES; 
     }else{ 
      self.addButton.enabled=NO; 
     } 
     return YES; 
    } 

    @end 
Cuestiones relacionadas