Custom Render for Picker - iOS

nnovalbos 371 Reputation points
2023-02-15T14:50:08.4+00:00

Hi,

I would like to modify the Picker that is displayed for iOS. I need to be able to add a 'Close' button to close the picker without selecting anything (I can't click on the view behind it as it has a touch event)

Thanks

Developer technologies | .NET | Xamarin
0 comments No comments
{count} votes

Accepted answer
  1. Wenyan Zhang (Shanghai Wicresoft Co,.Ltd.) 36,436 Reputation points Microsoft External Staff
    2023-02-16T03:53:39.5133333+00:00

    Hello,
    You can add a close button on the toolBar, and it can close the picker without selecting anything, please refer to the following code:

    public class CustomPickerRenderer:PickerRenderer
        {
            protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
            {
                base.OnElementChanged(e);
                if (Control != null)
                {
                    UIToolbar toolbar = (UIToolbar)Control.InputAccessoryView;
                    var closeButton = new UIBarButtonItem(UIBarButtonSystemItem.Close, (s, a) =>
                    {
                        Control.ResignFirstResponder();
                        UpdateCharacterSpacing();
                    });
                    List<UIBarButtonItem> oldItems = toolbar.Items.ToList();
                   // oldItems.Add(closeButton);
                    oldItems.Insert(0, closeButton);//the new button will be positioned on the left side of the toolbar
                    UIBarButtonItem[] newItems = oldItems.ToArray();
                    toolbar.SetItems(newItems, false);
                }
            }
        }
    

    Best Regards,

    Wenyan Zhang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.