在兼容 iOS 9 时编写代码需注意一些规则。
以纯代码的方式构造
UITableViewCell
当我们使用 RegisterClassForCellReuse 注册 Cell,用 DequeueReusableCell 获取 Cell, 如果此时 Cell 需要构造则默认会调用 initWithStyle:reuseIdentifier: 方法创建
[Export ("initWithStyle:reuseIdentifier:")]
public TestTableViewCell (UITableViewCellStyle style, NSString reuseIdentifier)
: base (style, reuseIdentifier)
{
}
UITableViewHeaderFooterView
当我们使用 RegisterClassForHeaderFooterViewReuse 注册 HeaderFooterView,用 DequeueReusableHeaderFooterView 获取 HeaderFooterView , 如果此时 HeaderFooterView 需要构造则默认会调用 initWithReuseIdentifier: 方法创建
[Export("initWithReuseIdentifier:")]
public AddAddressSectionHeader(NSString reuseIdentifier) : base(reuseIdentifier)
{
}
UICollectionViewCell
当我们使用 RegisterClassForCellReuse 注册 Cell,用 DequeueReusableCell 获取 Cell, 如果此时 Cell 需要构造则默认会调用 initWithFrame: 方法创建
[Export ("initWithFrame:")]
public TestCollectionViewCell (CGRect frame)
: base (frame)
{
}
可以通过基类实现查看更多 Export 的方法。
以 xib + cs 构造
- 当我们使用
xib文件布局构造UITableViewCell或UICollectionViewCell - 当自定义继承
UIView的子类,并通过布局视图的class方式引用时
需添加 initWithCoder: 方法
[Export ("initWithCoder:")]
public TestView (NSCoder coder)
:base(coder)
{
}
Reason: The initWithCoder: constructor is the one called when loading a view from an Interface Builder Xib file. If this constructor is not exported unmanaged code can’t call our managed version of it. Previously (eg. in iOS 8) the IntPtr constructor was invoked to initialize view.