我如何使用 dynamicType 在 swift3 中做 "perform(selector:)"
How can i use dynamicType to do "perform(selector:)" in swift3
在某些情况下:tableView 有不止一种类型的 UItableViewCell,并且这些 cell 实现了功能 "setData(_:)"。
所以,在
"tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell".
我可以用
"perfrom(selector:)"
避免“swift类型转换(如
if indexPath.row == 1{ cell as! SomeCoustomCell })".
但是如果我使用
"#selector()"
我仍然需要知道电池的类型并使用
"SomeCoustomCell.setData(_:)".
因此,我通过使用解决了它
"cell.perform(Selector("setData:"), with: dataSource[indexPath.row]["data"])"
虽然有警告。
swift 中的正确方法是什么??
使用perfrom(selector:)
不是最好的方法。您可以使用 协议 。像
protocol Configurable{
func setData(_ data: String)
}
您所有的自定义 tableView 单元格都应符合此协议。然后在 cellForRowAtIndexpath
if cell is Configurable{
cell.setData(data)
}
在某些情况下:tableView 有不止一种类型的 UItableViewCell,并且这些 cell 实现了功能 "setData(_:)"。 所以,在
"tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell".
我可以用
"perfrom(selector:)"
避免“swift类型转换(如
if indexPath.row == 1{ cell as! SomeCoustomCell })".
但是如果我使用
"#selector()"
我仍然需要知道电池的类型并使用
"SomeCoustomCell.setData(_:)".
因此,我通过使用解决了它
"cell.perform(Selector("setData:"), with: dataSource[indexPath.row]["data"])"
虽然有警告。
使用perfrom(selector:)
不是最好的方法。您可以使用 协议 。像
protocol Configurable{
func setData(_ data: String)
}
您所有的自定义 tableView 单元格都应符合此协议。然后在 cellForRowAtIndexpath
if cell is Configurable{
cell.setData(data)
}