根据 this Xamarin docs page ,我正在 Xamarin iOS 应用程序中构建 TableView :
- 自定义
UITableViewSource
类,覆盖GetCell()
、NumberOfSections()
和RowsInSection()
- 自定义
UITableViewCell
,实现采用IntPtr
的构造函数以启用单元格重用 - 在 View Controller 中调用
myTableView.RegisterClassForCellReuse()
,为其指定我自定义的UITableViewCell
这似乎有效。但是,我想使用具有非默认样式的单元格。作为the next page in the docs说明,UITableViewCellStyle
有几个选项,我想使用 UITableViewCellStyle.Value2
。现在,UITableViewCell
有一个采用 UITableViewCellStyle
选项的构造函数,但我不能使用它,因为单元格重用需要我实现 IntPtr
构造函数,而且我没有看到任何可从内部可用于设置样式的构造函数访问的内容。
有没有办法在不使用 UITableViewCell(UITableViewCellStyle style, NSString reuseIdentifier)
构造函数的情况下选择不同的 UITableViewCellStyle
选项?
最佳答案
我认为不使用 UITableViewCell(UITableViewCellStyle style, NSString reuseIdentifier) 构造函数就不可能加载不同的 UITableViewCellStyle 选项。此构造函数加载底层 XIB。
您提到“非默认样式”,使用您自己的自定义 UITableViewCell 可以让您自由地根据需要设计布局,添加标签、图像等。在 CustomUITableViewCell 内创建一个公共(public)方法,然后您可以定义如何显示内容,如下所述。
UITableView
public class CustomTableView : UITableView
{
static readonly NSString MyCellId = new NSString ("CustomTableViewCell");
public CustomTableView ()
{
RegisterClassForCellReuse(typeof(CustomTableViewCell), MyCellId);
Source = new CustomDataSource();
}
}
UITableViewCell
public class CustomTableViewCell : UITableViewCell
{
public CustomTableViewCell (IntPtr handle) : base (handle)
{}
public Load(object[] data){
//Create custom view in code
var title = new UILabel();
// etc.
// Or pull in from an XIB
UINib Nib = UINib.FromName ("CustomViewCell_iPad", NSBundle.MainBundle);
}
}
UITableViewSource
public class CustomTableDataSource : UITableViewSource
{
private NSString MyCellId { get; set; }
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
var cell = (CustomTableViewCell)tableView.DequeueReusableCell (MyCellId, indexPath);
cell.load(sampleData[indexPath.row]);
return cell;
}
}
关于c# - 在使用 IntPtr 构造函数进行单元重用时设置 Xamarin UITableViewCellStyle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29917078/