0

我有一个视图控制器,它包含 n 个UITextFieldsand UItextViewsUILabels如果它们中的任何一个发生变化,我是否可以得到通知..?

我可以通过手动查看它们各自TextDidChangeNotification和相似的方式来做到这一点,但我正在寻找一种更优化的方式来做到这一点,我不必担心它们中的每一个。

4

3 回答 3

3
// Assumes you don't use tag values now - if you do small change to create
// and index set, add the ones you use, so all new ones assigned are unique.
// assumes ARC

1) 新伊瓦尔:

{
    NSMutableDictionary *savedValues; 
}

1)当您想要基线值时:

savedValues = [self snapshot];

2)最初将其称为基线当前值,然后在以后的任何时间点:

- (NSMutableDictionary *)snapshot
{
    NSInteger tag = 1;
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:[self.view.subviews count]];

    for(UIView *v in self.view.subviews) {
        if([v isKindOfClass:[UILabel class]] || [v isKindOfClass:[UITextField class]] || [v isKindOfClass:[UITextView class]]) {
            if(v.tag == 0) v.tag = tag++; // will happen once
            // EDIT below
            [dict setObject:[NSString stringWithString:[(id)v text]] forKey:[NSNumber numberWithInteger:tag]];
        }
    }
    return dict;
}

4)当您想查看是否有任何变化时:

- (BOOL)anyChanges
{
    NSDictionary *currentDict = [self snapshot];
    return [currentDict isEqualToDictionary:savedValues];
}
于 2012-08-27T13:39:31.817 回答
0

让您的类处理文本字段中的 UIControlEventValueChanged 事件,文本视图或标签的值发生更改。添加这一行 ViewDidLoad 方法:

  [youLabel addTarget:self action:@selector(valueChanged:) 
          forControlEvents:UIControlEventValueChanged];  
  // add for textfield, textview also if needed
  [youTextField addTarget:self action:@selector(valueChanged:) 
          forControlEvents:UIControlEventValueChanged];
  [youTextView addTarget:self action:@selector(valueChanged:) 
          forControlEvents:UIControlEventValueChanged];

现在当值改变时会调用选择器

- (void) valueChanged:(id)sender{
  if(sender isKindofClass[UILabel class])
  {
    //label value changed here to differntiate used tag
    if([sender tag] == 0) 
     ....
     ....
  }
  else if(sender isKindofClass[UITextField class])
  {
    // textField value changed to differntiate used tag
    if([sender tag] == 0) 
     ....
     ....
  }
  else if(sender isKindofClass[UITextView class])
  {
    // textview value changed to differntiate used tag
    if([sender tag] == 0) 
     ....
     ....
  }
 }
于 2012-08-27T12:51:54.333 回答
0

您应该对所有文本字段、文本视图和标签使用一种方法。并给 textFields 和 textViews 和标签一个唯一的标签。这可以帮助您定义它的 textField、textView 或 Label。

if(sender.tag == 1000)//UILabel
{

    UILabel *label=(UILabel *)sender

      //write own code for label what do you want.

}
 else if(sender.tag == 2000)//UITextField
{
    UITextField *textField=(UITextField *)sender

      //write own code for textField what do you want.

}
else if(sender.tag == 3000)// UITextView
{
    UITextView *textView=(UITextView *)sender

      //write own code for textView what do you want.

}
于 2012-08-27T13:01:24.480 回答