Edit: I checked the similar question, but that's passing self
:
var buttonAction: ((UITableViewCell) -> Void)?
@IBAction func buttonPressed(_ sender: Any) {
buttonAction?(self)
}
While I'm no passing anything
I have a UICollectionView
full of cells that contain UITextField
s.
This is what my cell looks like:
class SearchCell: UICollectionViewCell {
@IBOutlet weak var textField: UITextField!
var startedEditing: (() -> Void)?
var endedEditing: (() -> Void)?
}
extension SearchCell: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
startedEditing?()
}
func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) {
endedEditing?()
}
}
I'm assigning the UITextField
delegate to SearchCell
. Whenever a delegate function is called, I call a closure.
I then add a print
statement to the closure inside collectionView(_:cellForItemAt:)
:
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as? SearchCell {
cell.startedEditing = { [weak self] in /// do I need weak self here?
print("\(indexPath) started editing")
}
cell.endedEditing = { [weak self] in /// or here?
print("\(indexPath) ended editing")
}
}
}
}
My question is, do I need [weak self]
inside the closure? Currently, I'm not even referencing self
(I just get the indexPath
), and Xcode says "Variable 'self' was written to, but never read." But, isn't the flow currently collectionView(_:cellForItemAt:)
→ SearchCell
→ collectionView(_:cellForItemAt:)
-- which seems like it captures something...
Should it be [weak collectionView]
? Or, if I change it to:
cell.startedEditing = { [weak self] in
print("\(indexPath) started editing")
self?.callSomeFunction()
}
Is [weak self]
appropriate there?
Thanks in advance!