gpt4 book ai didi

ios - 为什么我无法从类的实例中获取属性?

转载 作者:行者123 更新时间:2023-11-30 11:50:22 27 4
gpt4 key购买 nike

我有一个使用布局对象定义的 CollectionViewController 实例。

    let layout = UICollectionViewFlowLayout()
(1)let friendsController = FriendsController(collectionViewLayout: layout)
window?.rootViewController = UINavigationController(rootViewController: friendsController)

所以在friendsController中我定义了字符串属性消息。

class FriendsController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
fileprivate let cellId = "cellId"
var messages: [Message]?


override func viewDidLoad() {

super.viewDidLoad()
navigationItem.title = "Recent"
collectionView?.backgroundColor = UIColor.white
collectionView?.register(MessageCell.self, forCellWithReuseIdentifier: cellId)
collectionView?.alwaysBounceVertical = true
setupData()

}
......

是的,我可以从 (1)friendsController 获取消息。但是我定义了 FriendController 类的实例,它定义了空的初始值设定项,但我无法获取 messages 属性。我建议我启动了 UIViewCollectionController 类的父类,但是当看到有关 FriendController 类的附加信息(用空初始化程序初始化)时,它告诉我它仍然是 类 FriendsController :UICollectionViewController、UICollectionViewDelegateFlowLayout。如果有人可以给出提示,这会对我有很大帮助

最佳答案


1.解决方案:您可以在FriendsController中创建自定义初始化程序


class FriendsController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
fileprivate let cellId = "cellId"
var messages: [Message]?

init(collectionViewLayout layout: UICollectionViewLayout, and messages: [String]) {
super.init(collectionViewLayout: layout)
self.messages = messages
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}


override func viewDidLoad() {

super.viewDidLoad()
navigationItem.title = "Recent"
collectionView?.backgroundColor = UIColor.white
collectionView?.register(MessageCell.self, forCellWithReuseIdentifier: cellId)
collectionView?.alwaysBounceVertical = true
setupData()

}

然后

    let messages: [Message] = []
let layout = UICollectionViewFlowLayout()
let friendsController = FriendsController(collectionViewLayout: layout, and: messages)
window?.rootViewController = UINavigationController(rootViewController: friendsController)
  • 解决方案:只需在第一个代码中添加一行即可
  •     let messages: [Message] = []
    let layout = UICollectionViewFlowLayout()
    let friendsController = FriendsController(collectionViewLayout: layout, and: messages)
    friendsController.messages = messages
    window?.rootViewController = UINavigationController(rootViewController: friendsController)

    关于ios - 为什么我无法从类的实例中获取属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48385980/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com