gpt4 book ai didi

c# - 使用两个相似的 Collection View 单元格,从而避免代码重复

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:41:01 24 4
gpt4 key购买 nike

我想要两个几乎相似的单元格。区别仅在于多显示一个 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");

最佳答案

也许你考虑一个具有共享变量和方法的抽象类(将其命名为 BaseClass)和另外两个继承自抽象类的类,在代码中你可以将 cell 定义为一个对象并在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com