我希望能夠在IB中設計自己的UITableViewCell。 但是當我嘗試訪問我在IB中定義的標籤時,我總是收到null ref異常。如何使用Interface Builder中的自定義UITableViewCell?
下面是我在做什麼:
在Interface Builder:
- 我刪除了 「查看」,添加一個UITableViewCell代替。
- 將UITableViewCell的類更改爲「
TestCellView
」。 - 在單元格中添加了一個UILabel。
- 增加了一個插座「
oLblText
」到TestCellView
並將UILabel連接到它。 - 將類的標識符更改爲「TestCellView」。
實施TestCellView.xib.cs
public partial class TestCellView : UITableViewCell
{
public TestCellView(string sKey) : base(UITableViewCellStyle.Default, sKey)
{
}
public TestCellView(IntPtr oHandle) : base(oHandle)
{
}
public string TestText
{
get
{
return this.oLblText.Text;
}
set
{
// HERE I get the null ref exception!
this.oLblText.Text = value;
}
}
}
**的** TestCellView.designer.cs
[MonoTouch.Foundation.Register("TestCellView")]
public partial class TestCellView {
private MonoTouch.UIKit.UILabel __mt_oLblText;
#pragma warning disable 0169
[MonoTouch.Foundation.Connect("oLblText")]
private MonoTouch.UIKit.UILabel oLblText {
get {
this.__mt_oLblText = ((MonoTouch.UIKit.UILabel)(this.GetNativeField("oLblText")));
return this.__mt_oLblText;
}
set {
this.__mt_oLblText = value;
this.SetNativeField("oLblText", value);
}
}
}
在我的表的來源:
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
TestCellView oCell = (TestCellView)tableView.DequeueReusableCell("myCell");
if(oCell == null)
{
// I suppose this is wrong but how to do it correctly?
// this == my UITableViewSource.
NSBundle.MainBundle.LoadNib("TestCellView", this, null);
oCell = new TestCellView("myCell");
}
oCell.TestText = "Cell " + indexPath.Row;
return oCell;
}
請注意,我不想要一個涉及每個單元格的UIViewController的解決方案。我在網上看到過幾個例子。我只是認爲這是完全過度的。
我在做什麼錯?
這正是我現在所擁有的。我只是不喜歡有一個控制器。原因是:使用默認單元格樣式時,我也沒有控制器。所以,蘋果決定不需要控制器。創建自定義單元格時,他們希望我們每個單元格都有一個控制器。 – Krumelur 2011-03-21 09:11:47
是的,當您使用默認單元格樣式時,不需要任何控制器,因爲單元格是以編程方式創建的。但是您想要使用從NIB文件加載的單元,通常爲用戶界面對象。只需將一個自定義單元放在NIB文件中是不夠的。它必須以某種方式與它的文件所有者連接,在這種情況下,它必須是一個UIViewController。 – 2011-03-22 08:47:26