0
votes

I'm trying to make a simple listView with Xamarin Forms. The listView works in android, but on iOS i get a bugg where the content is missplaced over the cells. See my image and code below:

enter image description here

This is my code:

Page

public class TablePage
{
    public static Page GetTablePage ()
    {
        //Get NewsItems to populate listView
        var NewsItemList = DataAccessLayer.GetNewsItemList ();

        ListView listView = new ListView {
            ItemsSource = NewsItemList,
            ItemTemplate = new DataTemplate (typeof(NewsCell))
        };

        return new ContentPage { 
            Content = new StackLayout {
                Children = {
                    listView
                }
            },
            Title = "Table",
        };
    }
}

Cell:

public class NewsCell : ViewCell
    {
        public NewsCell ()
        {
            var headerLabel = new Label();
            var contentLabel = new Label();

            headerLabel.SetBinding(Label.TextProperty, "header");
            contentLabel.SetBinding(Label.TextProperty, "content");

            var s = new StackLayout();
            s.Padding = 20;
            s.Children.Add(headerLabel);
            s.Children.Add(contentLabel);

            this.View = s;
        }
    }

DataAccessLayer for items:

public static List<NewsItem> GetNewsItemList()
{
    List<NewsItem> NewsItemList = new List<NewsItem> ();
    NewsItemList.Add(new NewsItem { header = "News1", content = "content1"});
    NewsItemList.Add(new NewsItem { header = "News2", content = "content2"});
    NewsItemList.Add(new NewsItem { header = "News3", content = "content3"});
    NewsItemList.Add(new NewsItem { header = "News4", content = "content4"});
    return NewsItemList;
}

What am i doing wrong?

1
I'd recommend reducing the Padding on your StackLayout - either that or setting the RowHeight of your ListView to be larger to accomodate all that Paddingrwisch45

1 Answers

3
votes

The issue here is the padding you've used is 20px, much too large.

Take a look at this article to see what Padding is - it is the space between your container element and the space where child elements are laid out.

In this case you're putting 20px on either side, so the headerLabel starts 20px below the top, takes something like 20px itself and the contentLabel starts under that. At the same time the ListView still has its default row height, looks like something around 42px, so the contentLabel starts at offset of 40px and therefore over the next cell.

You can change your Padding to s.Padding = new Thickness(20,2,20,2); so that you get 20px on left and right but only 2 on top and bottom.


You will also notice that your ListView starts from the top of the screen and the iOS bar covers some of the content. To fix that apply a similar padding trick to the content page itself:

if (Device.OS == TargetPlatform.iOS)
    this.Padding = new Thickness (0, 20, 0, 0);