Xamarin Forms - How to create custom render to giv

2019-03-04 06:48发布

问题:

I want to add the default iOS footer to the tablesection in the tableview in Xamarin Forms. How can I go about doing this? I assume a customer renderer but I'm only reading that this can be done for Tableview?

To show an example, the following image is from Xcode storyboards when I enter the footer text on a static cell.

回答1:

A Custom renderer is right, but you will have to use a custom renderer for the entire TableView. From there, you will need to override the TableViewModelRenderer and then the GetViewForFooter method in that ModelRenderer. Here's something that might help get you started:

public class FooterTableViewRenderer : TableViewRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<TableView> e)
    {
        base.OnElementChanged(e);
        if (Control == null)
            return;

        var tableView = Control as UITableView;
        var formsTableView = Element as TableView;
        tableView.WeakDelegate = new CustomFooterTableViewModelRenderer (formsTableView);
    }


    private class CustomFooterTableViewModelRenderer : TableViewModelRenderer
    {
        public CustomFooterTableViewModelRenderer(TableView model) : base(model)
        {
        }

        public override UIView GetViewForFooter(UITableView tableView, nint section)
        {
            return new UILabel()
            {
                Text = TitleForFooter(tableView, section), // or use some other text here
                TextAlignment = UITextAlignment.Center
            };
        }

    }
}

As mentioned in my comments below, you can alternatively override other methods in your TableViewModelRenderer:

        public override nfloat GetHeightForFooter(UITableView tableView, nint section)
        {
            return 10;
        }

        public override string TitleForFooter(UITableView tableView, nint section)
        {
            return "This is the title for this given section";
        }