【问题标题】:How do you change the UIControl with focus on iPhone?你如何改变 UIControl 并专注于 iPhone?
【发布时间】:2010-10-02 20:16:41
【问题描述】:

我正在尝试做一些我认为很简单的事情。

我有一个带有两个 UITextField 的表单。我在第一个上使用 UIReturnKeyNext 样式。这个想法是,当用户填写第一个字段时,他们单击下一步,我将它们转换到下一个 UITextField。我见过其他应用程序可以做到这一点,而且效果非常好。但我不知道如何将焦点设置到下一个字段。

【问题讨论】:

    标签: cocoa-touch


    【解决方案1】:

    简单。将 becomeFirstResponder 消息发送到您的其他文本字段。当另一个文本字段接受第一响应者状态时,它将接收来自键盘的信息。

    例如:

    //called when the next button is pressed
    //Assume textField1, 2, and 3 are instances of UITextField
    -(IBAction) nextPressed: (id) sender {
          if ([textField1 isFirstResponder]) {
             [textField2 becomeFirstResponder];
          }
          if ([textField2 isFirstResponder]) {
             [textField3 becomeFirstResponder];
          }
    
    }
    

    【讨论】:

    • 这也是我的第一个想法,但我被文档弄糊涂了,文档清楚地说明 becomeFirstResponder 用于在 UIResponder 即将成为第一响应者时通知他们。在 Mac OSX 上,NSResponder 禁止直接调用 becomeFirstResponder。但是,事实证明你是对的。
    • 你是否将 nextPressed 链接到每个文本字段(在上面的示例中,它将链接到 textField1、2、3)???
    • 是的,如果您使用界面构建器,您可以将所有文本字段的“Touch Up Inside”操作链接到相同的 nextPressed 方法,同时将每个文本字段连接到自己的 IBOutlet(textField1、textField2、等)
    • 使用“Touch Up Inside”对我不起作用。我试过了,还有“编辑结束”......什么都没有:(
    • 我发现另一个问题的答案更复杂stackoverflow.com/questions/1347779/…
    【解决方案2】:

    上面的答案很有效,但您希望从原始文本字段中退出FirstResponder。

    如果您不辞退第一响应者,当下一个字段成为第一响应者时,IOS 自动滚动调整将不起作用。 (键盘可能会覆盖下一个文本字段。)

    -(IBAction) nextPressed: (id) sender {
    
        //Resign first so that when the next field becomes firstResponder 
        //the text field will scroll into place if covered by the keyboard
        [sender resignFirstResponder];      
    
        if ([textField1 isFirstResponder]) {
           [textField2 becomeFirstResponder];
        }
        if ([textField2 isFirstResponder]) {
           [textField3 becomeFirstResponder];
        }
    }
    

    【讨论】:

    • 等一下……什么iOS自动滚动调整?!?我一直看到你必须自己处理这样的滚动。我这里有一个简单的应用程序,上面有几个 UITextField,当键盘盖住它们时,它们当然不会滚动到视图中。我错过了什么?
    • 这是IOS内置的。很确定您的文本字段需要位于 UIScrollView 内部的视图中。
    • 啊,好吧,也许这是 UIScrollView 的一种行为......这会有些道理。不过,在其他情况下并不是特别有用。
    猜你喜欢
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多