Ios 如何使用UITableViewCell作为参数创建函数?
我想知道我们是否可以创建一个动态函数来访问单元格模板(xib模板),以实现如下动态:Ios 如何使用UITableViewCell作为参数创建函数?,ios,swift,uitableview,Ios,Swift,Uitableview,我想知道我们是否可以创建一个动态函数来访问单元格模板(xib模板),以实现如下动态: func create_image(TemplateName:??? = TemplateCell) { var cell = self.tableView.cellForRow(at: currindexpath as IndexPath) as! TemplateName } 我想传递带有UITableViewCell类名称的“TemplateName”: class template1: UIT
func create_image(TemplateName:??? = TemplateCell) {
var cell = self.tableView.cellForRow(at: currindexpath as IndexPath) as! TemplateName
}
我想传递带有UITableViewCell类名称的“TemplateName”:
class template1: UITableViewCell {
}
在这个参数上,我可以传递我创建的任何模板单元格。可能吗?抱歉,很难解释。您确实可以在函数中传递
TemplateCell
。例如:
func yourMethodForCell(_ cell: TemplateCell){
cell.backgroundColor = .red
}
然后按如下方式致电:
yourMethodForCell(cell)
一句话:不。斯威夫特不是你想要的那种动态的。唯一可以追求
as的东西
是一个实际的文本类型名称,而不是对将在变量或参数中传递的类型的某种引用
作为替代方案,您可以将单元格出列,然后询问单元格的类型,从而安全、明确地放弃:
let cell = // ... dequeue the cell as a UITableViewCell
if let cell = cell as? MyTableViewCell {
// here, cell is a MyTableViewCell now
}
使用switch语句而不是if
,可以对所有不同的单元格子类执行此操作
I have done this in one my sample project: Here is the sample code-
func setCardLayoutAccordingToId(cell: UITableViewCell,layoutId:Int) -> UITableViewCell {
let cgRect: CGRect = cell.contentView.frame
var layoutView: Any = DefaultCardView(frame: cgRect)
switch layoutId {
case 1:
layoutView = DefaultCardView(frame:cgRect)
case 2:
layoutView = Template_1(frame:cgRect)
case 3:
layoutView = Template_2(frame:cgRect)
case 4:
layoutView = Template_3(frame:cgRect)
default:
layoutView = DefaultCardView(frame:cgRect)
(layoutView as! DefaultCardView).setData(cardData: data)
}
for view in (cell.contentView.subviews)!{
view.removeFromSuperview()
}
cell.contentView.viewWithTag(1)?.addSubview(layoutView as! UIView)
(layoutView as! UIView).translatesAutoresizingMaskIntoConstraints = false
let attributes: [NSLayoutAttribute] = [.top, .bottom, .right, .left]
NSLayoutConstraint.activate(attributes.map {
NSLayoutConstraint(item: (layoutView as! UIView), attribute: $0, relatedBy: .equal, toItem: (layoutView as! UIView).superview, attribute: $0, multiplier: 1, constant: 0)})
return cell }
注:布局Id可根据您的需要决定。为什么需要创建单独的功能?你可以在单元格类中使用闭包作为代理。嗯,如果我回答不正确,很抱歉..因为可能每行单元格都有不同的模板布局…因此我需要创建此Dynamic是..因此我们仍然需要手动捕获布局ID,我希望可以直接使用类名来传递参数..但这是一个很好的例子..谢谢!似乎是正确的…仍然需要手动进行比较…所以没有办法这样做…谢谢!