2011-06-13 14 views
13

Estoy teniendo el peor momento para obtener la observación de valor clave trabajando con una propiedad de texto de UITextView. Puedo agregar al observador con éxito, incluso puedo eliminar ese mismo observador. Tengo una vista de tabla con varias celdas, algunas tienen UITextFields, algunas tienen UISegmentSelectors y una tiene UITextView. TODOS los demás campos son observados con éxito por mi objeto de datos central (subclase de NSMangedObject) EXCEPTO por UITextView. Puedo publicar el código si es necesario.¿Obtiene la observación de valor clave en la propiedad de texto de UITextView?

Código Publicado:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
static NSString *UserProfileCellIdentifier = @"UserProfileCellIdentifier"; 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: 
         UserProfileCellIdentifier]; 
if (cell == nil) 
{ 
    [_tableCellsNib instantiateWithOwner:self options:nil]; 

    switch (indexPath.row) 
    { 
      // UserName Row 
     case UserNameRowIndex: 
      _textFieldCell.cellLabel.text = NSLocalizedString(@"UserNameLabel", @"User Profile TableView"); 
      _textFieldCell.cellType = CellTypeNormal; 
      _textFieldCell.boundProperty = @"UserName"; 
      _textFieldCell.tag = indexPath.row; 
      _textFieldCell.errorHandler = self; 
      _textFieldCell.boundControl = _textFieldCell.cellTextField; 

      [_textFieldCell addObserver:[MBUtilities getAppDelegate].userProfile forKeyPath:@"cellTextField.text" options:NSKeyValueObservingOptionNew context:NULL]; 

      cell = _textFieldCell; 

      self.textFieldCell = nil; 
      break; 
     case PasswordRowIndex: 
      _textFieldCell.cellLabel.text = NSLocalizedString(@"PasswordLabel", @"User Profile TableView"); 
      _textFieldCell.cellType = CellTypeNormal; 
      _textFieldCell.cellTextField.secureTextEntry = YES; 
      _textFieldCell.boundProperty = @"Password"; 
      _textFieldCell.tag = indexPath.row; 
      _textFieldCell.errorHandler = self; 
      _textFieldCell.boundControl = _textFieldCell.cellTextField; 

      [_textFieldCell addObserver:[MBUtilities getAppDelegate].userProfile forKeyPath:@"cellTextField.text" options:NSKeyValueObservingOptionNew context:NULL]; 

      cell = _textFieldCell; 

      self.textFieldCell = nil; 
      break; 
     case PasswordConfirmRowIndex: 
      _textFieldCell.cellLabel.text = NSLocalizedString(@"PasswordConfirmLabel", @"User Profile TableView"); 
      _textFieldCell.cellType = CellTypeNormal; 
      _textFieldCell.cellTextField.secureTextEntry = YES; 
      _textFieldCell.tag = indexPath.row; 

      cell = _textFieldCell; 

      self.textFieldCell = nil; 
      break; 
     case FirstNameRowIndex: 
      _textFieldCell.cellLabel.text = NSLocalizedString(@"FirstNameLabel", @"User Profile TableView"); 
      _textFieldCell.cellType = CellTypeNormal; 
      _textFieldCell.boundProperty = @"FirstName"; 
      _textFieldCell.tag = indexPath.row; 
      _textFieldCell.errorHandler = self; 
      _textFieldCell.boundControl = _textFieldCell.cellTextField; 

      [_textFieldCell addObserver:[MBUtilities getAppDelegate].userProfile forKeyPath:@"cellTextField.text" options:NSKeyValueObservingOptionNew context:NULL]; 
      cell = _textFieldCell; 

      self.textFieldCell = nil; 
      break; 
     case LastNameRowIndex: 
      _textFieldCell.cellLabel.text = NSLocalizedString(@"LastNameLabel", @"User Profile TableView"); 
      _textFieldCell.cellType = CellTypeNormal; 
      _textFieldCell.boundProperty = @"LastName"; 
      _textFieldCell.tag = indexPath.row; 
      _textFieldCell.errorHandler = self; 
      _textFieldCell.boundControl = _textFieldCell.cellTextField; 

      [_textFieldCell addObserver:[MBUtilities getAppDelegate].userProfile forKeyPath:@"cellTextField.text" options:NSKeyValueObservingOptionNew context:NULL]; 
      cell = _textFieldCell; 

      self.textFieldCell = nil; 
      break; 
     case DateOfBirthRowIndex: 
      _textFieldCell.cellLabel.text = NSLocalizedString(@"BirthDateLabel", @"User Profile TableView"); 
      _textFieldCell.cellType = CellTypeDatePicker; 
      _textFieldCell.boundProperty = @"DateOfBirth"; 
      _textFieldCell.tag = indexPath.row; 
      _textFieldCell.errorHandler = self; 
      _textFieldCell.boundControl = _textFieldCell.cellTextField; 

      [_textFieldCell addObserver:[MBUtilities getAppDelegate].userProfile forKeyPath:@"cellTextField.text" options:NSKeyValueObservingOptionNew context:NULL]; 
      cell = _textFieldCell; 

      self.textFieldCell = nil; 
      break; 
     case GenderSelfRowIndex: 
      _genderSelectCell.cellLabel.text = NSLocalizedString(@"UserSexLabel", @"User Profile TableView"); 
      _genderSelectCell.boundProperty = @"GenderSelf"; 
      _genderSelectCell.errorHandler = self; 
      _genderSelectCell.boundControl = _genderSelectCell.cellGenderSegment; 
      _genderSelectCell.tag = indexPath.row; 

      [_genderSelectCell addObserver:[MBUtilities getAppDelegate].userProfile forKeyPath:@"cellGenderSegment.selectedSegmentIndex" options:NSKeyValueObservingOptionNew context:NULL]; 
      cell = _genderSelectCell; 

      self.genderSelectCell = nil; 
      break; 
     case GenderInterestedInRowIndex: 
      _genderSelectCell.cellLabel.text = NSLocalizedString(@"UserInterestedInLabel", @"User Profile TableView"); 
      _genderSelectCell.boundProperty = @"GenderInterestedIn"; 
      _genderSelectCell.errorHandler = self; 
      _genderSelectCell.boundControl = _genderSelectCell.cellGenderSegment; 
      _genderSelectCell.tag = indexPath.row; 

      [_genderSelectCell addObserver:[MBUtilities getAppDelegate].userProfile forKeyPath:@"cellGenderSegment.selectedSegmentIndex" options:NSKeyValueObservingOptionNew context:NULL]; 
      cell = _genderSelectCell; 

      self.genderSelectCell = nil; 
      break; 
     case IntroductionRowIndex: 
      _textViewCell.cellLabel.text = NSLocalizedString(@"IntroductionLabel", @"User Profile TableView"); 
      _textViewCell.boundControl = _textViewCell.cellTextView; 
      _textViewCell.errorHandler = self; 
      _textViewCell.boundProperty = @"Introduction"; 
      _textViewCell.tag = indexPath.row; 

      [_textViewCell addObserver:[MBUtilities getAppDelegate].userProfile forKeyPath:@"cellTextView.text" options:NSKeyValueObservingOptionNew context:NULL]; 
      cell = _textViewCell; 

      self.textViewCell = nil; 
      break; 
    }; 
} 

return cell; 
} 

Discusión: Cada célula se carga desde un archivo externo SEMILLA luego inicializado con diferentes propiedades. Todas las celdas funcionan con la observación del valor clave excepto la última con UITextView. Avíseme si se necesita información adicional.

Respuesta

15

UIKit no se garantiza que sea KVO compliant:

Nota: Aunque las clases del marco UIKit generalmente no son compatibles con MVA, todavía se puede aplicar en los objetos personalizados de su aplicación, incluida la costumbre puntos de vista.

Podría funcionar en algunas clases + teclas pero eso no es confiable, y podría cambiar en las diferentes versiones de iOS. Ver Dave’s answer to this question; Dave trabaja en UIKit.

+0

¿Cómo implementaría esto en una vista personalizada? ¿Qué método anularía para cambiar este comportamiento? – jjm340

+0

@jjm Solo puede implementar esto para claves personalizadas; por ejemplo, si declara una nueva propiedad. Si tiene una vista personalizada que hereda de una clase UIKit, KVO no necesariamente funcionará para las claves que ya existen en esa clase UIKit. –

0

¿Intentó implementar el UITextViewDelegate y le asignó el thisIsYourTextView.delegate?

Bueno, encontré esto tutorial, tal vez hará las cosas un poco más claras.

+0

Sí, lo hago en el constructor de interfaz (o lo que sea que se llame a la versión 4.0 xCode) – jjm340

+0

¿Podría publicar un código para su controlador, entonces? Puede ser más fácil ayudar con una ayuda visual. –

+0

Haré. Gracias. – jjm340

3

Ok, así que no tuve la suerte de encontrar ninguna explicación para este comportamiento y, a menos que alguien pueda decirme lo contrario, creo que es un error en IOS.

que era capaz de conseguir que funcione con este truco:

- (void)textViewDidEndEditing:(UITextView *)textView 
{ 
    NSLog(@"Editing Ended"); 
    textView.text = textView.text; 
} 

Una vez añadido el código, voila, los incendios observeValueForKeyPath!

+0

Esto no es un error. Siendo el UITextView no KVO garantizado, posiblemente ellos internamente establezcan el valor usando el iVar. En su lugar, está estableciendo explícitamente el valor de la variable mediante el establecimiento de propiedades y este SÍ garantiza que se activarán los eventos KVO. – SalvoC

14

Usar UITextViewTextDidChangeNotification es mejor.

hice lo siguiente:

primer registro con NSNotificationCenter:

- (id)init 
{ 
    [super init]; 
    if (self) 
    { 
     NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 
     [nc addObserver:self 
       selector:@selector(textDidChange:) 
        name:UITextViewTextDidChangeNotification 
       object:nil]; 
    } 
    return self; 
} 

- (void)dealloc 
{ 
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 
    [nc removeObserver:self]; 
} 

a continuación, definir un controlador de notificación:

- (void)textDidChange:(NSNotification *)note 
{ 
    NSLog(@"Observation..."); 
} 

Ahora cada vez que el texto en el objeto cambia UITextView, la textDidChange: método será llamado.

+0

Incluso puede verificar si esa vista de texto es su vista de texto: 'UITextViewTextDidChangeNotification Notifica a los observadores que el texto en una vista de texto ha cambiado. La vista afectada se almacena en el parámetro de objeto de la notificación. El diccionario userInfo no se usa. –

Cuestiones relacionadas