2017-02-02 4 views
0

Я создал UITableViewCell, но при установке источника UITableView, я получаю NullReferenceException.Xamarin IOS UITableView.Source NullReferenceException

public partial class SessionOverviewViewController : UIViewController 
{ 

    public List<BaseSessionController> Sessions; 

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

    public override void ViewDidLoad() 
    { 
     base.ViewDidLoad(); 
     tvTable.RegisterClassForCellReuse(typeof(SessionTableViewCell), "SessionCell"); 
     SessionTableViewSource source = new SessionTableViewSource(Sessions); 
     tvTable.Source = source; //This line throws the Exception 
    } 
} 

TableViewSource:

public class SessionTableViewSource : UITableViewSource 
{ 
    List<BaseSessionController> TableItems; 
    string CellIdentifier = "SessionCell"; 

    public SessionTableViewSource(List<BaseSessionController> items) 
    { 
     TableItems = items; 
    } 

    public override nint RowsInSection(UITableView tableview, nint section) 
    { 
     return TableItems.Count; 
    } 

    public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) 
    { 
     SessionTableViewCell cell = (SessionTableViewCell)tableView.DequeueReusableCell(CellIdentifier); 
     BaseSessionController friend = TableItems[indexPath.Row]; 

     //---- if there are no cells to reuse, create a new one 
     if (cell == null) 
     { 
      //cell = new SessionTableViewCell(new NSString(CellIdentifier), friend.FriendName, new UIImage(NSData.FromArray(friend.FriendPhoto))); 
      cell = new SessionTableViewCell(new NSString(CellIdentifier), friend); 
     } 

     //cell.UpdateCellData(friend.UserName, new UIImage(NSData.FromArray(friend.FriendPhoto))); 

     return cell; 
    } 
} 

И сам сотовый

public partial class SessionTableViewCell : UITableViewCell 
{ 
    public BaseSessionController Session; 

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

    public SessionTableViewCell(NSString cellId, BaseSessionController session) : base(UITableViewCellStyle.Default, cellId) 
    { 
     Session = session; 
     lblDate.Text = Session.Model.SessionStartTime.ToString("d"); 
    } 
} 

Надеюсь кто-то может увидеть ошибку, которую я сделал, и может помочь мне с этим.

Заранее спасибо

+0

Вы можете отлаживать и проверять выполнение GetCell или RowsInSection? или "источник" не является нулевым? – Darshana

+0

Кстати, у вас есть ячейка с идентификатором «SessionCell» в раскадровке или xib? Я думаю, что проблема – Darshana

+0

Оба метода не выполняются, и я проверяю 'source'. Это определенно не null, также выход 'UITableView' не является нулевым и т. Д. И да, я устанавливаю идентификатор внутри Storyboard –

ответ

1

После просмотра раскадровки, это было обнаружено, что tvTable фактически представляет собой прокрутку. Неудачно бесполезное сообщение об ошибке :)

+0

Чрезвычайно бесполезно, но большое спасибо за помощь! –

0

вы должны зарегистрировать клетку UITableView

tvTable.RegisterClassForCellReuse(typeof(SessionTableViewCell), "SessionCell"); 

изменить код

public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) 
{ 
    SessionTableViewCell cell = (SessionTableViewCell)tableView.DequeueReusableCell(CellIdentifier); 
    BaseSessionController friend = TableItems[indexPath.Row]; 


    cell.Session = friend; 

    return cell; 
} 

и

public partial class SessionTableViewCell : UITableViewCell 
{ 
    private BaseSessionController _session; 
    public BaseSessionController Session 
    { 
     get { return _session; } 
     set 
     { 
      _session = value; 
      if(value != null) 
      { 
       lblDate.Text = value.Model.SessionStartTime.ToString("d"); 
      } 
     } 
    } 

    public SessionTableViewCell (IntPtr handle) : base (handle) 
    { 
    } 
} 
+0

Строка' cell = new SessionTableViewCell(); 'будет создавать некоторые проблемы, потому что мне нужно предоставить 'IntPtr' Variable –

+0

Извините, вы должны удалить' if (cell = null) 'см. Мое обновление ответа – sunyt

+0

Хорошо, но я все равно получаю ту же ошибку в той же строке –

0

Вы можете попробовать это:

В ViewDidLoad:

public override void ViewDidLoad() 
{  
    base.ViewDidLoad(); 
    SessionTableViewSource source = new SessionTableViewSource(Sessions); 
    tvTable.Source = source; 
} 

В вашем TableViewSource ->GetCell поставить это:

public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) 
{ 
    BaseSessionController friend = TableItems[indexPath.Row]; 
    var cell = tableView.DequeueReusableCell ("SessionCell") as SessionTableViewCell; 
    cell.Update(friend); 
    return cell; 
} 

И в вашем SessionTableViewCell поставить это:

public void UpdateCell(BaseSessionController friend) 
{ 
    Session = session; 
    lblDate.Text = Session.Model.SessionStartTime.ToString("d"); 
} 
+0

Он по-прежнему падает с помощью NullReferenceException:/ –

+0

@ Daniel Попробуйте изменить' GetCell', чтобы просто вернуть 'new UITableViewCell();' и посмотреть, что произойдет – angak

+0

Это просто выбрасывает одно и то же исключение, потому что GetCell не вызывается до 'tvTable.Source = source;' –

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

  • Нет связанных вопросов^_^