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