kformeck kformeck - 3 months ago 24
C# Question

How Do I Add/Remove a UIBarButtonItem to/from a UIToolbar After Items Have Already Been Added?

I am working in Xamarin.iOS and I have UIToolbar that needs to be able to add and remove buttons from it programmatically at run-time.

I have tried several different approaches using: _buttons is a UIBarButtonItem[]

SetItems(_buttons, false)

and the toolbar never seems to update.

I initialize the toolbar when the app starts up with its main three buttons. When certain things happen, I need to be able to remove buttons from the toolbar as well as add new items to the toolbar.

I have also tried calling:


after calling:

SetItems(_buttons, false)

and this doesn't update the toolbar items either.

Any suggestions?


And the reason it is not changing because LayoutSubviews is called all the time and overrides your SetItems. Use constructor to populate toolbar first time

public partial class CustomUiToolbar : UIToolbar
    public CustomUiToolbar (IntPtr handle) : base (handle)
        var _UIBarButtonItemArrayOne = new UIBarButtonItem[3];
        for (int i = 0; i < 3; i++)
            var _item = new UIBarButtonItem(i.ToString(), UIBarButtonItemStyle.Done, null);
            _item.TintColor = UIColor.Red;
            _UIBarButtonItemArrayOne[i] = _item;
        //var __UIBarButtonItemArrayTwo = new UIBarButtonItem[2];
        //for (int i = 0; i < 2; i++)
        //    var _item = new UIBarButtonItem(i.ToString(), UIBarButtonItemStyle.Done, null);
        //    _item.TintColor = UIColor.Blue;
        //    __UIBarButtonItemArrayTwo[i] = _item;
        SetItems(_UIBarButtonItemArrayOne, true);

    public override void LayoutSubviews()