某些背景
假设我必须显示一个可以包含各种类型的组件的表单:
我为每个对象创建了UITableViewCell
,但是由于它们都是表单组件,并且每个元素都具有一些共同的属性,例如某些数据(formData,userEntered数据),因此我制定了协议并遵循了所有这些条件此协议的单元格
protocol FormComponent where Self: UITableViewCell {
var property1: String? { get set }
var property2: String? { get set }
}
并且像这样使我的细胞适应了
class TextFieldCell: UITableViewCell, FormComponent {
var property1: String?
var property2: String?
}
问题
现在,当我必须决定必须创建哪个UITableViewCell
时,我必须做出switch语句并确定要创建哪个表单组件
// Some field that I get from some computation and this same will go inside every cell no matter the type
let field = computeFieldValue()
switch fieldType {
case textField:
let cell = tableView.dequeueReusableCell(withIdentifier: TEXT_FIELD_CELL, for: indexPath) as! TextFieldCell
cell.property1 = field.property1
cell.property2 = field.property2
return cell
case textArea:
let cell = tableView.dequeueReusableCell(withIdentifier: TEXT_AREA_CELL, for: indexPath) as! TextAreaCell
cell.property1 = field.property1
cell.property2 = field.property2
return cell
}
现在而不是初始化单元格并在交换机的case
中分配属性,我想使用协议优势将交换机外部的单元格初始化为sort-of协议类型,以便我可以分配开关外部的属性值,无需为每种情况下的属性分配相同的值
// Some field that I get from some computation and this same will go inside every cell no matter the type
let field = computeFieldValue()
var cell = // cell initialisation which will be of type FormComponent so that I can access the property values directly from here
cell.property1 = field.property1
cell.property2 = field.property2
switch fieldType {
case textField:
// Converting that cell to TextFieldCell with the properties defined above intact
case textArea:
// Converting that cell to TextAreaCell with the properties defined above intact
}
return cell
我认为这有点像上播,我不确定如何实现。并且,如果有一些属性特定于单个fieldType,我也许可以贬低为cell as! TextFieldCell
部分中的case
,然后分配它>
而且我有很多属性和很多case(fieldType)可以处理,所以这种方法会减少很多代码
某些背景,假设我必须显示一种可以包含各种类型的组件的表单:文本字段文本区域图像视频下拉菜单我已经为每个对象创建了UITableViewCell,但由于它们......>
[每当我尝试利用Swift功能简化开发并使之更加有趣时,UIKit始终确保使其变得超硬甚至不可能,以使其容易灰心和沮丧。
您想要实现的目标是每个应用都有其自己的解决方案,因为有很多方法可以解决此问题,并且许多解决方案都可以使用适合其需求的解决方案(具体情况因项目而异。 )。就我而言,在我目前正在从事的项目中,我已应用此策略来实现表格视图: