简体   繁体   中英

How to handle accessory button tap on iOS in Xamarin.Forms?

There's a AccessoryButtonTapped method to override in table view delegate, but it's not clear how to perform that in a ListViewRenderer subclass?

So I can display a disclosure indicator, but can't handle tap on it.

public class ContactCellRenderer : ImageCellRenderer
{
    public override UITableViewCell GetCell (
        Cell item, UITableViewCell reusableCell, UITableView tv)
    {
        var cell = base.GetCell (item, reusableCell, tv);
        cell.Accessory = UITableViewCellAccessory.DetailDisclosureButton;
        return cell;
    }
}

I think, you have just to implement the method AccessoryButtonTapped in your renderer.

public class ContactListViewRenderer : ListViewRenderer, IUITableViewDelegate
{
    protected override void OnElementChanged(ElementChangedEventArgs<ListView> e)
    {
        base.OnElementChanged(e);
        if (Control != null)
        {
            Control.WeakDelegate = this; // or. Control.Delegate
        }
    }

    public virtual void AccessoryButtonTapped(UITableView tableView, NSIndexPath indexPath)
    {
        // accessory tapped
    }
}

In addition to Sven-Michael, you can enrich his code by creating a inheritance of your ListView (if you do not already have one) and add a Delegate to it like this:

public class AccessoryListView : ListView
{
   public delegate void OnAccessoryTappedDelegate();

   public OnAccessoryTappedDelegate OnAccessoryTapped { get; set; }
}

Now from your custom renderer - don't forget to set it to your new inherited ListView - call the delegate

public class ContactListViewRenderer : ListViewRenderer, IUITableViewDelegate
{
    private AccessoryListView _formsControl;

    protected override void OnElementChanged(ElementChangedEventArgs<AccessoryListView> e)
    {
        base.OnElementChanged(e);
        if (Control != null)
        {
            Control.WeakDelegate = this; // or. Control.Delegate
        }

        if (e.NewElement != null)
           _formsControl = e.NewElement;
    }

    public virtual void AccessoryButtonTapped(UITableView tableView, NSIndexPath indexPath)
    {
        // accessory tapped
        if (_formsControl.OnAccessoryTapped != null)
           _formsControl.OnAccessoryTapped();
    }
}

You can of course add some parameters in there to supply your shared code with more data. With this you do have some platform specific code, but you get back to your shared code 'as soon as possible' making your code more reusable.

Another sample of this with a Map control can be found here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM