我想要两个几乎相似的单元格。不同之处仅在于在其上显示更多 View 。
因此我想使用自定义构造函数。通常你有一个类似于这个的构造函数:
public class AnimalCell : UICollectionViewCell
{
[Export ("initWithFrame:")]
public AnimalCell (CGRect frame) : base (frame)
{
// do something
}
}
我想传递一个类型,根据这个类型,我想在单元格上显示不同的项目。最好的方法是使用这样的构造函数:
public AnimalCell(MyCustomType type)
{
if(type == XXX){
// add as subview, add constraints, ...
}else{
// normal setup
}
}
我当然想保持单元重复使用。这可以实现吗?怎么样?
我想到的另一件事是使用子类化。有谁知道我如何定义 cell 以便我不必复制相同的代码?例如
var cell = null;
if (MyCustomType == XXX) {
cell = collectionView.DequeueReusableCell (DefaultCell.Key, indexPath) as DefaultCell;
} else {
cell = collectionView.DequeueReusableCell (CustomizedCell.Key, indexPath) as CustomizedCell;
}
cell.DoSomething("someValue"); // this doesn't work because you have to define cell with a certain class
// do some more initialization
我目前的解决方案:
public abstract class DefaultCell : UICollectionViewCell
{
protected bool someVariable;
[Export ("initWithFrame:")]
public DefaultCell (CGRect frame) : base (frame)
{
}
public void DoSomething(string text)
{
label.Text = text;
}
}
public class Custom1Cell : DefaultCell
{
public static readonly NSString Key = new NSString ("Custom1Cell");
[Export ("initWithFrame:")]
public Custom1Cell (CGRect frame) : base (frame)
{
initialize ();
}
private void initialize()
{
// some initialization
}
}
public class Custom2Cell : DefaultCell
{
public static readonly NSString Key = new NSString ("Custom2Cell");
[Export ("initWithFrame:")]
public Custom2Cell (CGRect frame) : base (frame)
{
initialize ();
}
private void initialize()
{
// some initialization
}
public void SomeMethod(string text)
{
if(someVariable)
someOtherLabel.Text = text;
}
}
Mahmoud 描述的出队工作:
DefaultCell cell;
if (type = XXX) {
cell = collectionView.DequeueReusableCell (Custom1Cell.Key, indexPath) as Custom1Cell;
} else {
cell = collectionView.DequeueReusableCell (Custom2Cell.Key, indexPath) as Custom2Cell;
}
cell.DoSomething("works on both cell types");
((Custom2Cell)cell).SomeMethod("works only on one cell type");
Best Answer-推荐答案 strong>
也许您考虑一个具有共享变量和方法的抽象类(将其命名为 BaseClass)和其他两个从抽象类继承的类,在代码中您可以将单元格定义为对象并在 if 语句中对其进行初始化,如下所示:
Object cell;
if (MyCustomType == XXX) {
cell = new class1()
((Class1) cell).MethodInClass1();
} else{
cell = new class2();
((Class2) cell).MethodInClass2();
}
关于c# - 使用两个相似的 Collection View 单元,从而避免代码重复,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/29628838/
|