清除新细胞:
因为我不理解一个100%你的问题,我认为你的问题是,新的细胞得到cell_1,这是不是你想要的东西的价值。
如果是这种情况,那么在UICollectionViewCell
中有一个称为prepareForReuse
的函数。 在你的UICollectionViewCell
的子类,具有如下功能:
override func prepareForReuse() {
super.prepareForReuse()
textfield.text = ""
}
这应该做的伎俩,因为你的textfield
被称为textfield
。
执行任何必要的清理操作以准备再次使用该视图。 https://developer.apple.com/reference/uikit/uicollectionreusableview/1620141-prepareforreuse
更新所有单元格:
如果你的问题是如何更新其他细胞获得相同的内容cell_1,那么这意味着集合视图子类需要了解在更新cell_1,然后将该更新转换为其他单元格。 这样做的一种方法是在集合视图中设置您的textfield
的委托。当值更改(textField(_:shouldChangeCharactersIn:replacementString:)
)时,获取所有可见单元格并相应地更新那些textfields
。也许还可以在cell_1中保存对textfield
的引用,或者在集合视图中保存一个字符串变量,说明最新输入的值,以便可以在显示单元格时更新单元格。 你不要虽然想使用reloadData()
,因为这将从textField
删除焦点,因为textField
重新加载。
解决方案:
class ViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
fileprivate var customString: String?
}
extension ViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell
cell.textField.delegate = self
cell.textField.text = customString
return cell
}
}
extension ViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
customString = string
for cell in collectionView.visibleCells {
if let cell = cell as? CustomCell,
let text = textField.text,
cell.textField != textField {
cell.textField.text = text+string
}
}
return true
}
}
在上面的代码唯一con是,它遍历当前可见细胞。通常我会建议不要循环,除非绝对必要,但上面解决方案的替代方法是发布通知并让单元监听该通知并相应地更新其内容。这样做不仅会矫枉过正,而且还有一些通知并非真正意义上的。第三种选择是将数组中的弱引用保存到每个文本字段中,这可能不是最优的,因为它会产生不必要的开销。毕竟visibleCells
已经是当前可见的单元格阵列,每个单元格都拥有对UITextField
的引用。
我不是完全跟着你,只要是你的问题,所有的细胞得到** ** cell_1的价值,或者是你希望所有的细胞更新到** cell_1值**为您在** cell_1 **中输入“textfield”中的内容? –
@PaulPeelen我想我在cell_1 – javimuu