我有一个UITableView
。它有两个自定义原型单元。现在只有一个单元格被修复,它只会在tableview中保留一个,但是另一个单元格将再次添加到tableview中。再次按下按钮。
下面是tableview方法的代码:
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr_fields.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cellIndentifier="property"
let cell:CreatePropertyCell=tableView.dequeueReusableCell(withIdentifier: cellIndentifier, for: indexPath) as! CreatePropertyCell
cell.layer.borderWidth = 2.0
cell.layer.borderColor = UIColor.gray.cgColor
cell.txt_propertyName.attributedPlaceholder = NSAttributedString(string:"Name of property",
attributes:[NSForegroundColorAttributeName: UIColor.gray])
return cell
} else {
let cellIdentifier = "attribute"
let cell:AddProperty=tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! AddProperty
cell.layer.borderWidth = 2.0
cell.layer.borderColor = UIColor.gray.cgColor
cell.txt_AddProperty.attributedPlaceholder = NSAttributedString(string:"Property Attribute",
attributes:[NSForegroundColorAttributeName: UIColor.gray])
cell.btnAdd.tag=indexPath.row
return cell
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 15
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = UIView()
header.backgroundColor = UIColor.clear
return header
}
@IBAction func actionAddProperty(_ sender: AnyObject) {
let cellIdentifier = "attribute"
let cell:AddProperty = self.tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! AddProperty
cell.layer.borderWidth = 2.0
cell.layer.borderColor = UIColor.gray.cgColor
cell.txt_AddProperty.attributedPlaceholder = NSAttributedString(string:"Property Attribute",
attributes:[NSForegroundColorAttributeName: UIColor.gray])
cell.tag=sender.tag!+1
arr_fields.append(cell)
tableView.reloadData()
print("tag is \(sender.tag!)")
}
现在我只想在表视图中添加第二个单元格而不是两个单元格。到目前为止,它将两个单元格添加到表格视图中。
答案 0 :(得分:0)
试试这个:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
} else {
return arr_fields.count
}
}
插入单元格:不是重新加载表格,而是将一个单元格插入表格中:
@IBAction func actionAddProperty(_ sender: AnyObject) {
let cellIdentifier = "attribute"
let cell:AddProperty = self.tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! AddProperty
cell.layer.borderWidth = 2.0
cell.layer.borderColor = UIColor.gray.cgColor
cell.txt_AddProperty.attributedPlaceholder = NSAttributedString(string:"Property Attribute",
attributes:[NSForegroundColorAttributeName: UIColor.gray])
cell.tag=sender.tag!+1
let indexPath = NSIndexPath.init(forRow: arr_fields.count-1, inSection: 1)
tableView.beginUpdates()
arr_fields.append(objComment)
tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
tableView.endUpdates()
}