【问题标题】:How to change cell label from another class (View Controller)?如何从另一个类(视图控制器)更改单元格标签?
【发布时间】:2017-11-09 12:37:27
【问题描述】:

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

如果您还有其他问题,请告诉我,谢谢!

【问题讨论】:

  • 没有人向选择器发送参数!你能发布崩溃日志吗?
  • @Yitzchak 我已经添加了崩溃日志!
  • 您应该将参数发送给函数,并且需要更新函数以从参数中获取标签,我在上面添加的链接
  • @Yitzchak 好的,所以我不需要使用协议和委托,对吧?

标签: ios iphone swift xcode uicollectionview


【解决方案1】:

像这样在视图控制器中定义函数:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多