所以我正在尝试从 Collection View Controller 更改 Collection View 单元格类中的喜欢标签。我尝试使用协议(protocol)、委托(delegate)和通知中心来完成它,但是当我尝试从我的 View Controller 配置 likes 标签时,我的应用程序因 lldb 而崩溃。 这是相关代码:
class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout, HomePostCellDelegate {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(refreshLikeButtonLabel(for:)), name: NSNotification.Name(rawValue: "refresh"), object: nil)
}
@objc func refreshLikeButtonLabel(for cell: HomePostCell) {
cell.likesLabel.text = "4"
print("is it working?")
}
}
细胞类:
protocol HomePostCellDelegate {
func refreshLikeButtonLabel(for cell: HomePostCell)
}
class HomePostCell: UICollectionViewCell {
lazy var likesLabel: UILabel = {
let label = UILabel()
label.font = UIFont(name: "AvenirNext-Regular", size: 20)
label.textColor = UIColor.black
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refresh"), object: nil)
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
这是控制台的内容:
2017-11-09 07:06:09.969144-0500 Vlogr[1200:24674] [Fabric] unable to complete application configure: Error Domain=FABNetworkError Code=-5 "(null)" UserInfo={status_code=422, type=2, request_id=84d6b91378f57956e1ae930e41915b46, content_type=text/html; charset=utf-8}
(lldb)
如果您有任何问题,请告诉我,谢谢!
最佳答案
像这样在 View Controller 中定义函数:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(reload(_:)), name: NSNotification.Name(rawValue: "refresh"), object: nil)
}
@objc func reload(_ notification: Notification) {
if let likesLabel = notification.userInfo?["likesLabelInfo"] as? UILabel {
likesLabel.text = "4"
}
}
在此处定义 Collection View 单元格中的标签:
lazy var likesLabel: UILabel = {
let label = UILabel()
label.font = UIFont(name: "AvenirNext-Regular", size: 20)
label.textColor = UIColor.black
let userInfo = ["likesLabelInfo": label]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refresh"), object: nil, userInfo: userInfo)
return label
}()
关于ios - 如何从另一个类( View Controller )更改单元格标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47202069/