菜鸟教程小白 发表于 2022-12-11 19:45:41

ios - 设置变量后 UICollectionView 为零


                                            <p><p>设置变量时, Collection View 为零。如果我在 <code>viewDidLoad</code> 中运行,一切正常。我试图修复和搜索所有相关的帖子,但我无法通过它。 </p>

<p>这是我的相关代码:</p>

<pre><code>@IBOutlet var vnexpressContentCV: UICollectionView!
var link: String? {
      didSet {
             fetchData()
      }
    }
override func viewDidLoad() {
    super.viewDidLoad()
    print(&#34;viewDidLoad&#34;)
    vnexpressContentCV.register(UINib(nibName: &#34;VNExpressContentCollectionViewCell&#34;, bundle: nil), forCellWithReuseIdentifier: vnexpressContentCell)
    fetchData()
}
func fetchData() {
      SVProgressHUD.show()
      if let text = link {
            Alamofire.request(text).responseRSS() { (response) -&gt; Void in
                if response.result.isSuccess {
                  if let feed: RSSFeed = response.result.value {
                        self.items = feed.items

                        //this line below tells vnexpressContentCV is nil
                        self.vnexpressContentCV.reloadData()
                  }
                }
            }
      }
    }
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>它是 nil,因为当您通过创建此 ViewController 的实例从源 ViewController 设置 <code>var link: String</code> 的值时,当时 <code>didSet</code> 为 <code>var link: String</code> 会被调用,但是此时这个viewcontroller还没有加载UI组件。</p>

<p>您可以在 <code>didSet</code> 方法中检查 <code>vnexpressContentCV</code> 是否为 nil,以防止应用崩溃,</p>

<pre><code>didSet {
    if let vnexpressContentCV = vnexpressContentCV {
      fetchData()
    }
}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 设置变量后 UICollectionView 为零,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/48819849/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/48819849/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 设置变量后 UICollectionView 为零