Tom*_*zie 3 c# uitableview nullreferenceexception xamarin.ios xamarin
我正在为iOS创建一个Xamarin应用程序,我已经在故事板中添加了一个UITableViewCell,以赋予它我自己的风格.我确实为这个自定义UITableViewCell添加了一个类,即MainMenuCell.我向单元格添加了两个标签,并将它们与MainMenuCell.h文件连接起来,产生以下代码:
MainMenuCell.cs
using System;
using Foundation;
using UIKit;
namespace MyProjectNamespace
{
public partial class MainMenuCell : UITableViewCell
{
public MainMenuCell (IntPtr handle) : base (handle)
{
}
public MainMenuCell () : base ()
{
}
public void SetCellData()
{
projectNameLabel.Text = "Project name";
projectDateLabel.Text = "Project date";
}
}
}
Run Code Online (Sandbox Code Playgroud)
MainMenuCell.h(自动生成):
using Foundation;
using System.CodeDom.Compiler;
namespace MyProjectNamespace
{
[Register ("MainMenuCell")]
partial class MainMenuCell
{
[Outlet]
UIKit.UILabel projectDateLabel { get; set; }
[Outlet]
UIKit.UILabel projectNameLabel { get; set; }
void ReleaseDesignerOutlets ()
{
if (projectNameLabel != null) {
projectNameLabel.Dispose ();
projectNameLabel = null;
}
if (projectDateLabel != null) {
projectDateLabel.Dispose ();
projectDateLabel = null;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在我在这里有我的UITableViewSource,我正在尝试从GetCell方法初始化MainMenuCell:
using System;
using UIKit;
using Foundation;
namespace MyProjectNamespace
{
public class MainMenuSource : UITableViewSource
{
public MainMenuSource ()
{
}
public override nint NumberOfSections (UITableView tableView)
{
return 1;
}
public override string TitleForHeader (UITableView tableView, nint section)
{
return "Projects";
}
public override nint RowsInSection (UITableView tableview, nint section)
{
return 1;
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
MainMenuCell cell = new MainMenuCell();
cell.SetCellData ();
return cell;
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,它不断向我抛出System.NullReferenceException:
projectNameLabel.Text = "Project name";
Run Code Online (Sandbox Code Playgroud)
它说:对象引用未设置为对象的实例.
我在这里错过了什么?任何帮助将受到高度赞赏.
你几乎就在那里 - 不是自己创建一个新单元,而是让iOS完成工作并将结果出列.
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
var cell = (MainMenuCell)tableView.DequeueReusableCell("MainMenuCell");
cell.SetCellData();
return cell;
}
Run Code Online (Sandbox Code Playgroud)
请注意,"MainMenuCell"是Storyboard中动态原型单元的标识符,您可以根据需要为其命名,但它必须与Storyboard和您的数据源相同.

| 归档时间: |
|
| 查看次数: |
1785 次 |
| 最近记录: |