2013-04-11 5 views
2

У меня есть UITableView и подклассы UITableViewSource класс:UITableView RowSelected не вызывается?

table = new UITableView(window.Bounds); 
table.Source = new CellSource(); 

public class CellSource : UITableViewSource 
{ 
    // etc etc 

Я пытаюсь получить выбранную строку, так реализован метод RowSelected в моем исходном классе:

public override void RowSelected(UITableView tableview, NSIndexPath indexpath) { 
    Console.WriteLine("User tapped"); 
} 

Однако, нажав на ячейки не дают никакого ответа вообще, даже когда просто пытаются писать на консоль.

Я могу опубликовать полные классы, если это поможет?

Спасибо.

EDIT

Итак, после того, как я создаю мой UITableView:

table = new UITableView(window.Bounds); 
table.AutoresizingMask = UIViewAutoresizing.All; 
table.SeparatorStyle = UITableViewCellSeparatorStyle.None; 
table.BackgroundColor = UIColor.Clear; 
table.Source = new CellSource(); 

Я использую мой класс источника для разбора файла 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();  
} 

I затем создайте CGBitmapContext в другом классе, верните изображение и установите это как изображение ячеек:

public UIImage DrawCell (string cellImage) { 
    string cellI = cellImage; 
    //create a new graphics context 
    int width = 320; 
    int height = 110; 
    CGBitmapContext ctx = new CGBitmapContext(IntPtr.Zero, width, height, 8, 4*width, CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedFirst); 

    //load an image 
    var imagePath = (@cellI); 
    var image = UIImage.FromFile(imagePath).CGImage; 
    ctx.DrawImage(new RectangleF(0, 0, width, height), image); 

    UIImage returnedImage = new UIImage(); 
    returnedImage = FromImage(ctx.ToImage()); 

    return returnedImage; 
} 

добавить некоторые другие вещи, как тест на этикетке, и переопределить метод RowSelected:

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

public override void RowSelected(UITableView tableview, NSIndexPath indexpath) { 
    Console.WriteLine("User tapped"); 
} 
+0

Вы также назначаете делегату или источнику данных свой вид? – Jason

+0

Я предполагаю, что нет, у меня есть класс CellSource, который заполняет таблицу данными из XML. Я не могу найти ничего особенного в назначении DataSource, я Googled, но все примеры очень похожи на то, что я делаю уже. Спасибо за ответ. – mrEmpty

+0

вы делаете что-нибудь еще, когда вы создаете таблицу и назначаете свойства, или что вы все ее разместили? – Jason

ответ

2

В MonoTouch UITableViewSource является комбинированным UITableViewDataSource и UITableViewDelegate для UITableView. Таким образом, когда вы расширяете такой класс, вы можете использовать методы как в источнике данных, так и в делетете.

Сказал, что я немного изменил бы ваш код (см. Комментарии).

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

     // why do you set the interaction to false? Setting it to false disable interaction for your cell 
     cell.UserInteractionEnabled = true; 

     // create label and view here. You customize the cell with additional elements once 

    } 

    // update image and label here (you need to grab a reference for your label for example through the tag) 

    return cell; 
} 

Также обратите внимание на Working with Tables and Cells в документации Xamarin.

Надеюсь, это поможет.

Смежные вопросы