【问题标题】:How to programmatically deselect UITextField如何以编程方式取消选择 UITextField
【发布时间】:2015-07-24 21:26:48
【问题描述】:

我有一个UITextField,我可以点击它并编辑其中的内容。当按下 UITextField 时,我正在运行代码:

[personalCountryLabel addTarget:self action:@selector(countryPressed) forControlEvents:UIControlEventEditingDidBegin];  

这呈现了另一个视图控制器。但是,当我单击后退按钮时,UITextField 仍处于选中状态,因此文本再次运行,将我送回视图控制器。

我使用代码:

textField.enabled = false;

textField.enabled = true;

分别关闭和打开UITextField的编辑,但连续执行此操作不会取消选择UITextField

因此,我如何以编程方式取消选择 UITextField(即行光标不再闪烁的位置)。

【问题讨论】:

    标签: ios objective-c iphone uitextfield


    【解决方案1】:

    如果我理解您的要求正确,您只想:

    [textField resignFirstResponder];
    

    【讨论】:

    • 我试过这个,但不幸的是它没有奏效。如果我运行代码并注释掉后续的 segue,它所做的就是阻止光标闪烁。但是,UITextField 仍然处于选中状态,如果用户在键盘上输入值,仍然可以输入文本。
    • 键盘消失了吗?这是从 UITextField 断开键盘的标准 iOS 方法。
    • 是的,当我打开键盘并单击 UITextField 时,键盘仍然存在。日志显示代码肯定正在运行。
    • 艾萨克,你是在 iPad 上运行这个吗?
    • 另外,当您发送resignFirstResponder 消息时,您确定textField 不是nil
    【解决方案2】:

    /* 以编程方式取消选择此代码下方的 Uitextfiels */

    UITextField *txtDeselect = [[UITextField alloc]initWithFrame:CGRectMake(self.view.frame.origin.x+20, self.view.frame.origin.y+20, self.view.frame.size.width-40, 40)];
        [txtDeselect setBackgroundColor:[UIColor yellowColor]];
        [txtDeselect setBorderStyle:UITextBorderStyleRoundedRect];
        [txtDeselect setTextAlignment:NSTextAlignmentCenter];
        [txtDeselect setText:@"Email"];
        txtDeselect.enabled = NO;
        [self.view addSubview:txtDeselect];
    

    【讨论】:

      【解决方案3】:

      您是否在视图控制器中设置了 UITextField 的出口和委托? 你为什么要使用 UItextfield 呢?

      我建议您在展示新的视图控制器之前使用其中之一:

      选项 1:

      [youtextfield resignFirstResponder];
      

      //请确保您的插座已连接 & ....

      你可以在你的 viewWillAppear 上调用它

      选项 2:

      [self.view endEditing:YES]; // this regularly
      happend after present another VC)
      

      你不应该使用 shouldEndEditing

      【讨论】:

        猜你喜欢
        • 2016-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-05
        • 2013-04-03
        • 2014-01-24
        相关资源
        最近更新 更多