removeFromSuperview不适用于UIImageView

时间:2018-04-23 22:17:11

标签: ios swift uiview uiimageview

如果计数为零,我会通过以下代码将图像添加到我的视图中,否则将其删除:

var coverImageView = UIImageView()

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if count == 0 {
        let coverImage = UIImage(named: "AddFirstRecord")!
        coverImageView = UIImageView(image: coverImage)
        coverImageView.frame = CGRect(x: 20, y: 5, width: tableView.frame.width-20, height: 100)
        view.addSubview(coverImageView)

    } else {
        DispatchQueue.main.async {
            self.coverImageView.removeFromSuperview()
        }
    }
}

问题是它将图像添加到视图中,但removeFromSuperview不起作用。 (我通过调试确保它达到else条件。我也在主队列中完成了该过程,以确保该问题与线程无关。我想知道问题的根源在哪里?

1 个答案:

答案 0 :(得分:1)

viewWillAppear中,视图仍未完全准备好查看。所以removeFromSuperview没有任何影响。相反,我们应该在viewDidLayoutSubviews

中执行操作
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if fetchedResultsController.fetchedObjects?.count == 0 {
        let coverImage = UIImage(named: "AddFirstRecord")!
        coverImageView.image = coverImage
        coverImageView.frame = CGRect(x: 20, y: 5, width: tableView.frame.width-20, height: 100)
        view.addSubview(coverImageView)

    } else {
        coverImageView.removeFromSuperview()
    }
}

来自Apple Documentation

  

viewDidLayoutSubviews()   被调用以通知视图控制器它的   view刚刚列出了它的子视图。

     

您的视图控制器可以覆盖此方法以进行更改   该视图列出了其子视图。这个的默认实现   方法什么都不做。