简体   繁体   中英

Alternating row colors in UITableView

How do I get alternating row colors in a UITableView using monotouch?

I am currently populating my TableView using this:

public partial class myViewController : UITableViewController
    {
        public static UINavigationController navigationController;
        public static IntPtr handle;

        public CompanyViewController (IntPtr handle) : base (handle)
        {
        }


        public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();
            Services service = new Services();

            var myList = service.GetList(param1);

            List<string> list = new List<string>();
            foreach(var c in myList)
            {
                list.Add (c.Name);
            }

            navigationController = NavigationController;
            handle = Handle;
            var source = new CompanyTableSource(list);

            myTableView.Source = source;

        }

Add this class:

public class AlternatingTableViewDelegate : UITableViewDelegate
{
    public override void WillDisplay (UITableView tableView, UITableViewCell cell, NSIndexPath indexPath)
    {
        if (indexPath.Row % 2 == 0) {
            cell.BackgroundColor = UIColor.White;
        } else {
            cell.BackgroundColor = UIColor.LightGray;
        }
    }
}

Use it in you tableview:

var tvdelegate = new AlternatingTableViewDelegate()
myTableView .Delegate = tvdelegate

There's a better way to do this. All you need to do is to set the background color in the GetCell method, alternating the line color, as shown here. It also solves the problem of not handling touches on a line in the tableview.

public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) {
        if (indexPath.Row % 2 == 0) {
                ContentView.BackgroundColor = UIColor.DarkGray;
        } else {
                ContentView.BackgroundColor = UIColor.DarkTextColor;
        }
}

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