Have UITextField show keyboard (becomeFirstResponder) when UIView is shown

三世轮回 提交于 2019-12-24 09:02:13

问题


I have a UIViewController with a UITableView. The first row of the UITableView is a cell that has a UITextField in it. I'd like to improve my UI a little by showing the keyboard when the view is shown. I have tried putting the BecomeFirstResponder method in various events but have yet to get this to work.

Can someone please provide tips on how to present the keyboard when the view is presented via the PushViewController?

Thank you.


回答1:


In your subclass of UITableViewSource or UITableViewDelegate try overriding WillDisplay method, like this:

public override void WillDisplay (UITableView tableView, UITableViewCell cell, NSIndexPath indexPath)
{
  if(indexPath.Row == theRowIndexOfTheCellWithYourTextField){
    yourTextField.BecomeFirstResponder();
  }
}

It should work (note that you probably wish to add some code to make sure this is executed only once)




回答2:


First of all, always use a UITableViewController derived class instead of a UIViewController when working with a UITableView. This will help you to resize the view, and makes sure fields are visible when the keyboard is shown.

You can show the keyboard for the first field by calling BecomeFirstResponder in the ViewDidAppear event. Example:

public class YourTableViewController : UITableViewController
{
    private UITableView _yourTableView;
    YourUITableViewSourceDerivedClass _yourSource;

    public override void ViewDidLoad()
    {
        _yourTableView = new UITableView(View.Bounds, UITableViewStyle.Plain);
        _yourTableView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight;
        _yourSource = new YourUITableViewSourceDerivedClass();
        _yourTableView.Source = _yourSource;
        TableView = _yourTableView;
    }

    public override void ViewDidAppear(bool animated)
    {
        // Well, of course you call a method in your source to do this, but this is the idea:
        _yourSource.textFieldOnFirstRow.BecomeFirstResponder();
    }
}



回答3:


in your viewdidload, put this:

[yourTextField becomeFirstResponder];

I am not sure at all is this works :S

please tell if it does/don't :)




回答4:


You can try setting up a notification for when your cell view is loaded or appeared. Then you can call the becomeFirstResponder on the field after the notification is fired off.



来源:https://stackoverflow.com/questions/4402187/have-uitextfield-show-keyboard-becomefirstresponder-when-uiview-is-shown

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!