2012-12-04 42 views
2

如何使用monotouch在UITableView中獲得交替的行顏色?UITableView中的交替行顏色

我使用這個當前填充我的TableView:

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; 

     } 

回答

7

加入這個類:

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; 
     } 
    } 
} 

用它,在你實現代碼如下:

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

在此情況下應委託分配? – callisto

+0

在您的viewDidLoad,在這裏你還指定數據源 – svn

+0

你是一個搖滾明星! Upvoted並標記爲正確! – callisto

1

有一個更好的方式做這個。所有你需要做的是設置背景顏色在GetCell方法,交替行的顏色,如下所示。它還解決了在tableview中不處理觸摸行的問題。

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