Select an item in an iOS Picker using Xamarin UITest?

Solution 1:

A better solution is to write a UITest backdoor, and then in the backdoor find the Renderer for the Picker and control it directly.

The core to the solution was provided to me by @LandLu on the Xamarin forums:

You should obtain the current view controller first. Then iterate the subview to get your picker renderer. Here is my dependency service for you referring to:

[assembly: Dependency(typeof(FindViewClass))]
namespace Demo.iOS
{
    public class FindViewClass : IFindView
    {
        public void FindViewOfClass()
        {
            UIViewController currentViewController = topViewController();
            getView(currentViewController.View);
        }

        List<PickerRenderer> pickerList = new List<PickerRenderer>();
        void getView(UIView view)
        {
            if (view is PickerRenderer)
            {
                pickerList.Add((PickerRenderer)view);
            }
            else
            {
                foreach (UIView subView in view.Subviews)
                {
                    getView(subView);
                }               
            }
        }

        UIViewController topViewController()
        {
            return topViewControllerWithRootViewController(UIApplication.SharedApplication.KeyWindow.RootViewController);
        }

        UIViewController topViewControllerWithRootViewController(UIViewController rootViewController)
        {
            if (rootViewController is UITabBarController)
            {
                UITabBarController tabbarController = (UITabBarController)rootViewController;
                return topViewControllerWithRootViewController(tabbarController.SelectedViewController);
            }
            else if (rootViewController is UINavigationController)
            {
                UINavigationController navigationController = (UINavigationController)rootViewController;
                return topViewControllerWithRootViewController(navigationController.VisibleViewController);
            }
            else if (rootViewController.PresentedViewController != null)
            {
                UIViewController presentedViewController = rootViewController.PresentedViewController;
                return topViewControllerWithRootViewController(presentedViewController);
            }
            return rootViewController;
        }
    }
}

Once I've done that, I can select the index/item I want via the Element property of the Renderer.

Edit I've worked this up into a GitHub repository which implements a set of Backdoors to make iOS Picker selection easier