微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在collectionView_:cellForItemAt :)内部的闭包是否需要弱自身?

如何解决在collectionView_:cellForItemAt :)内部的闭包是否需要弱自身?

编辑:我检查了类似的问题,但是通过了self

var buttonAction: ((UITableViewCell) -> Void)?

@IBAction func buttonpressed(_ sender: Any) {
     buttonAction?(self)
}

我什么也没传递


我有UICollectionView个充满UITextField的单元格。 这是我的手机的样子:

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?()
    }
}

我正在将UITextField委托分配给SearchCell。每当调用委托函数时,我都会调用闭包。

然后我将print语句添加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")
            }
        }
    }
}

我的问题是,封包内是否需要[weak self]?目前,我什至没有引用self(我刚得到indexPath),Xcode说“变量'self'被写入,但从未读取。”但是,当前不是collectionView(_:cellForItemAt:)SearchCellcollectionView(_:cellForItemAt:)的流-似乎它捕获了某物 ...

应该是[weak collectionView]吗?或者,如果我将其更改为:

cell.startedEditing = { [weak self] in
    print("\(indexPath) started editing")
    self?.callSomeFunction()
}

[weak self]在这里合适吗?

谢谢!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。