如何从另一个类(View Controller)更改单元格标签?

时间:2017-11-09 12:37:27

标签: ios iphone swift xcode uicollectionview

所以我试图从集合视图控制器更改集合视图单元格类中的likes标签。我尝试使用协议和委托以及通知中心来做这件事,但是当我尝试从我的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) 

如果您有任何其他问题,请与我们联系,谢谢!

1 个答案:

答案 0 :(得分:1)

在视图控制器中定义函数,如下所示:

Absent

在此处的集合视图单元格中定义标签:

 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"
    }
}