Have UITextField show keyboard (becomeFirstRespond

2019-07-26 08:26发布

问题:

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.