2013-04-11 2 views
0

У меня есть UITableView, который заполняется изображениями и ярлыками. В моем классе источника я создаю UILabel для каждой ячейки:Xamarin/MonoTouch UITableView cache

public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath) 
    { 
     UITableViewCell cell = tableView.DequeueReusableCell (cellIdentifier); 

     //if there are no cells create a new one 
     if (cell == null) 
      cell = new UITableViewCell (UITableViewCellStyle.Default, cellIdentifier); 
     cell.UserInteractionEnabled = false; 

     //create a new cellobject - this grabs the image and returns a CGBitmapContext 
     CellObject _cellObject = new CellObject(); 
     cell.ImageView.Image = _cellObject.DrawCell(treasures[indexPath.Row].cellImage); 

     //add text 
     UILabel secondViewLabel = new UILabel(); 
     secondViewLabel.Text = treasures[indexPath.Row].cellTitle; 
     Console.WriteLine("The title is: " + treasures[indexPath.Row].cellTitle); 
     secondViewLabel.TextColor = UIColor.White; 
     secondViewLabel.TextAlignment = UITextAlignment.Center; 
     secondViewLabel.Lines = 0; 
     secondViewLabel.LineBreakMode = UILineBreakMode.WordWrap; 
     secondViewLabel.Font = UIFont.FromName("Helvetica", 16); 
     secondViewLabel.BackgroundColor = UIColor.FromRGB(205, 54, 51); 

     //get the width of the text 
     SizeF labelSize = secondViewLabel.StringSize(secondViewLabel.Text, secondViewLabel.Font); 

     secondViewLabel.Frame = new RectangleF(0, 110 - (labelSize.Height + 10), labelSize.Width + 20, labelSize.Height + 10); 

     //add a second view 
     UIView secondView = new UIView(); 
     secondView.AddSubview(secondViewLabel); 
     cell.ContentView.AddSubview(secondView); 


     return cell; 
    } 

который строит таблицу прекрасно, однако, кажется, что каждая клетка получает в UILabel для любой другой клетки, а также его собственный. Я вижу это на более коротких ярлыках, вы можете увидеть другие ярлыки. Я загрузка и разбор XML в список, и отработка этого списка:

List<Treasure> treasures = new List<Treasure>(); 

    protected class Treasure { 
     public string cellTitle { get; set; } 
     public string cellTag { get; set; } 
     public string cellImage { get; set; } 
     public string audioFile { get; set; } 
     public string mainTitle { get; set; } 
     public string mainTag { get; set; } 
     public string mainBody { get; set; } 
     public string mainImage { get; set; } 
     public string mainCaption { get; set; } 
    } 

    public CellSource (/*string[] items*/) 
    { 
     Console.WriteLine("CellSource called"); 
     string fileName = "treasuresiPhone.xml"; 
     XDocument doc = XDocument.Load(fileName); 
     treasures = doc.Descendants("treasures").FirstOrDefault().Descendants("treasure").Select(p=> new Treasure() { 
      cellTitle = p.Element("celltitle").Value, 
      cellTag = p.Element("celltagline").Value, 
      cellImage = p.Element("cellimage").Value 
     }).ToList(); 

     numCells = treasures.Count(); 

    } 

Любые идеи или советы будут оценены.

Спасибо.

ответ

1

Создания нового UILabel каждых GetCell вызова немного хромает:

  • Времени создания нового объекта UI и установить его свойство в наиболее часто называемом методе;
  • GC может съесть ваш UILabel Причина не явная ссылка на него существует.

Попробуйте другое решение:

  • Создайте свой собственный подкласс UITableViewCell;
  • Затем объявить UILabel имущество в нем;
  • Затем, когда ячейка dequeue попытается создать ячейку для вашего типа. Если это не значение null, установите для него свойство текста метки в новое значение.
0

Это, кажется, работает для меня:

public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath) 
    { 
     UITableViewCell cell = tableView.DequeueReusableCell (cellIdentifier); 

     cell = new UITableViewCell (UITableViewCellStyle.Default, cellIdentifier); 
     cell.UserInteractionEnabled = false; 
     UILabel secondViewLabel = new UILabel(); 

     //if there are no cells create a new one 
     if (cell == null) { 
      Console.WriteLine("cell == null"); 
     } else { 

      //create a new cellobject - this grabs the image and returns a CGBitmapContext 
      CellObject _cellObject = new CellObject(); 
      cell.ImageView.Image = _cellObject.DrawCell(treasures[indexPath.Row].cellImage); 

      //add text 
      secondViewLabel.Tag = 1; 
      secondViewLabel.Text = treasures[indexPath.Row].cellTitle; 
      Console.WriteLine("The title is: " + treasures[indexPath.Row].cellTitle); 
      secondViewLabel.TextColor = UIColor.White; 
      secondViewLabel.TextAlignment = UITextAlignment.Center; 
      secondViewLabel.Lines = 0; 
      secondViewLabel.LineBreakMode = UILineBreakMode.WordWrap; 
      secondViewLabel.Font = UIFont.FromName("Helvetica", 16); 
      secondViewLabel.BackgroundColor = UIColor.FromRGB(205, 54, 51); 

      //get the width of the text 
      SizeF labelSize = secondViewLabel.StringSize(secondViewLabel.Text, secondViewLabel.Font); 

      secondViewLabel.Frame = new RectangleF(0, 110 - (labelSize.Height + 10), labelSize.Width + 20, labelSize.Height + 10); 

      //add a second view 
      UIView secondView = new UIView(); 
      secondView.AddSubview(secondViewLabel); 
      cell.ContentView.AddSubview(secondView); 
     } 
     return cell; 
    } 
1

Если вы деактивируете ячейку, у вас уже есть подпункты (UILabels), которые вы добавили. Ячейка сериализована как целое, со всеми представлениями, которые вы добавили при создании. Итак: если вы не хотите подкласса UITableViewCell, назначьте значения тегов своим пользовательским представлениям и используйте ViewWithTag для доступа к ним.