ios 如何以编程方式提供 UITextView 焦点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/987975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 16:01:04  来源:igfitidea点击:

How do I give a UITextView focus programmatically?

iosobjective-ccocoa-touchuikit

提问by Meroon

So I want to bring in a modal view controller that has a UITextView in it and I want the keyboard to automatically popup and the UITextView have focus.

所以我想引入一个模态视图控制器,其中有一个 UITextView 并且我希望键盘自动弹出并且 UITextView 具有焦点。

I found a way to accomplish this by doing the following:

我通过执行以下操作找到了一种方法来完成此操作:

textView.editable = YES;
textView.editable = NO;

This just seems hacky to me, is there another way?

这对我来说似乎很hacky,还有其他方法吗?

回答by Alex Rozanski

Since UITextViewinherits from UIResponder(indirectly, it actually inherits from UIScrollView, which inherits from UIViewwhich theninherits from UIResponder) you can call the -becomeFirstRespondermethod on your text field, which will cause it to become the first responder and begin editing:

由于UITextView继承自UIResponder(间接地,它实际上继承自UIScrollView,继承自UIView然后继承自UIResponder)您可以-becomeFirstResponder在文本字段上调用该方法,这将使其成为第一响应者并开始编辑:

[textView becomeFirstResponder];

回答by Esqarrouth

Swift:

迅速:

textView.becomeFirstResponder()

回答by Erik

That does seem somewhat hackish.

这似乎有点骇人听闻。

The Cocoa Touch terminology for 'having focus' is 'first responder' and UITextViews will display their keyboards when they are the first responder. I can think of several techniques to make the UITextView become the first responder, but the easiest is probably in your view controller's viewWillAppear or viewDidAppear methods:

Cocoa Touch 中“具有焦点”的术语是“第一响应者”,UITextView当他们是第一响应者时,s 将显示他们的键盘。我可以想到几种使 UITextView 成为第一响应者的技术,但最简单的可能是在您的视图控制器的 viewWillAppear 或 viewDidAppear 方法中:

- (void)viewWillAppear:(BOOL)animated
{

    [myTextView becomeFirstResponder];

    [super viewWillAppear:animated];
}

回答by Corey Floyd

[textView becomeFirstResponder];

回答by Corey Floyd

When you want the focus to be that particular TextView on loading a ViewController, you can place the textView.becomeFirstResponder() in the ViewDidLoad overrode func as below:

当您希望焦点是加载 ViewController 时的特定 TextView 时,您可以将 textView.becomeFirstResponder() 放在 ViewDidLoad 覆盖函数中,如下所示:

 override func viewDidLoad() {
    super.viewDidLoad()

textView.becomeFirstResponder()

}

I find this works without any errors

我发现这没有任何错误

回答by Igor Monteiro

On Xamarin Forms Custom Render:

在 Xamarin Forms 自定义渲染上:

   protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
    {
        base.OnElementChanged(e);

        if (Control != null)
        {
            Control.BecomeFirstResponder();
        }
    }