我有一个包含多个部分的表格视图,每个部分中的行数不同。
我创建了一个自定义表格视图单元格。该单元格具有标签和文本字段。
此相同的自定义单元格用于表视图中的每个单元格。
当我在文本字段中输入一个值时,它会出现在其他一些文本字段以及其他行中。有时文本从我输入的文本字段中消失,并出现在下面的行中。当我上下滚动tableview时会发生这种情况。
这是我用于cellForRowAt的代码
let cell = tableView.dequeueReusableCell(withIdentifier: "LabelTextFieldTableViewCell", for: indexPath) as! LabelTextFieldTableViewCell
for i in approachSection {
if Int(i.row) == indexPath.row {
cell.myLabel.text = i.name
cell.myTextField.placeholder = cell.setPlaceholder(type: i.type!)
if i.type != CustomFieldType.text.rawValue {
cell.isInteger = true
}
}
}
return cell
自定义单元格是
class LabelTextFieldTableViewCell: UITableViewCell, UITextFieldDelegate {
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var myTextField: UITextField!
var isInteger: Bool?
var type: String!
override func awakeFromNib() {
super.awakeFromNib()
myTextField.delegate = self
myTextField.textAlignment = .right
myTextField.borderStyle = .none
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setPlaceholder(type: String) -> String {
switch type {
case CustomFieldType.count.rawValue:
return "#"
case CustomFieldType.time.rawValue:
return "Time as 1234"
case CustomFieldType.text.rawValue:
return "Enter Text"
default:
return ""
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.textColor = .black
}
func textFieldDidEndEditing(_ textField: UITextField) {
guard textField.text != "" else { return }
if isInteger != nil {
guard checkIfIntegers(str: textField.text!) != false else {
print("Not all Integers")
textField.textColor = .red
return
}
}
}
}
答案 0 :(得分:0)
在您的单元格子类中使用prepareToReuse方法。在这里,您应该将所有值重置为默认值,并在相应的cellForRowAtIndexPath方法中将适当的值设置为cell。
func prepareForReuse()
在您的LabelTextFieldTableViewCell
类中编写此方法
希望对您有帮助
快乐的编码=)
答案 1 :(得分:-1)
请确保您正确遵循此算法
注意:您可以在这些方法中使用switch语句来确定在特定部分显示多少行。
- tableView:cellForRowAtIndexPath: // required method
– tableView:numberOfRowsInSection: // required method
– numberOfSectionsInTableView:
– sectionIndexTitlesForTableView:
– tableView:sectionForSectionIndexTitle:atIndex:
– tableView:titleForHeaderInSection:
– tableView:titleForFooterInSection: