繁体   English   中英

UITextField本身成为第一响应者…?

[英]UITextField becomes first responder by itself…?

这只会在设备上发生,而不会在模拟器上发生。

我有两个自定义视图,并且两个视图中都有一个UITextField(Child1和Child2)。 这两个视图都放在另一个UIView上(说viewA)。 现在我的要求是,当在一个文本字段中输入文本时,我需要清除其他文本字段的内容,因此在textFieldDidChange:方法中,我通知viewA,然后对其子视图进行迭代,以查找Child1并设置其属性。 但是,一旦我访问此Child1的textField以启用其userInteraction或将其文本设置为nil。 现在,此文本字段成为第一响应者。

我不太确定为什么要这么做。 您可以查看以下代码以获取更多信息。

viewA中的方法:

  for (UIView *view in [self subviews])
    {
        if ([view isKindOfClass:[ChildView class]])
        {
            ChildView *concernedCustomerView = (ChildView *)view;
            if (concernedCustomerView.typeOfCompartment == CompartmentTypeNone)
            {
                [concernedCustomerView.checkBoxButton setSelected:NO];
                [concernedCustomerView.countSwitch setOn:NO animated:YES];
                concernedCustomerView.countTextField.userInteractionEnabled = YES;
                concernedCustomerView.countTextField.alpha = 1.0f;
                concernedCustomerView.countTextField.text = nil;
            }
        }
    }

自定义子视图中的方法

-(void)textFieldDidChange:(id)sender
{
    NSString *note = _countTextField.text;
    note = [note stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    //If we are checking note for nil it should be before calling trimming white space
    if (note && note.length > 0)
    {
        [_checkBoxButton setSelected:YES];
        if (note.length == 3 && note.integerValue == 999)
        {
            [_countSwitch setOn:YES animated:YES];
            _countTextField.userInteractionEnabled = NO;
            _countTextField.alpha = 0.5f;
            _countTextField.text = nil;
//           [_countSwitch sendActionsForControlEvents:UIControlEventValueChanged];
        }
    }
    else
    {
        [_checkBoxButton setSelected:NO];
    }

    if ([self.delegate conformsToProtocol:@protocol(ChildViewDelegate)] &&
        [self.delegate respondsToSelector:@selector(adjustStateOfOtherControls:andCheckBoxStatus:)])
    {
        [self.delegate adjustStateOfOtherControls:_typeOfCompartment andCheckBoxStatus:_checkBoxButton.selected];
    }
}

不要将视图对象设置为nil,因为它们仍然存在并且您的控制器仍处于活动状态,请尝试设置_countTextField.text = @""; 这样您的文本字段将变为空。

只是一个建议:

1)您可以将标记分配给子视图和uitextfield,而不是手动迭代子视图,例如:

child1View.tag = 100;
child2View.tag = 200;
...
textField1.tag = 10;
textField2.tag = 20;

然后通过以下方式从父级viewA获取子级引用:

 UIView *child1View = [viewA viewWithTag:100];
 UIView *child2View = [viewA viewWithTag:200];

2)将子视图文本字段委托设置为通用视图控制器

3)处理一个

  - (void)textFieldDidBeginEditing:(UITextField *)textField

4)检查这种方法

if(textField.tag==10)
{
  do stuff
}
else if(textfield.tag==20)
{
  do other stuff
}

希望能帮助到你 !

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM