簡體   English   中英

視圖未從iOS的超級視圖中刪除

[英]View not removed from its superview in iOS

我有一個UIViewcollectionView 如果有互聯網連接,我想隱藏collectionView並顯示UIView ,否則請隱藏。

class MyClass{
    @IBOutlet weak var collectionView: UICollectionView!
    var myView : CustomView?
    ....

    func internetStatusChanegd(){
        if(isOnline){
            collectionView.isHidden = true
            if let viewNib = UIView.loadFromNibNamed("CustomView", bundle: Bundle.main) as? CustomView {
                myView = viewNib
                myView!.frame = self.view.bounds
                self.view.addSubview(myView!)
            }
        }else{
            if let customView = myView{
                customView.removeFromSuperview()
            }
            collectionView.isHidden = false
        }
    }
}

removeFromSuperview()被調用,但視圖並未從視圖中移除。 您對這個問題有想法嗎?

像這樣刪除

for subview in self.view.subviews{
   if subview is CustomView
   {
      subview.removeFromSuperview()
   }
}
  1. 在我的視圖中添加子視圖時,給該視圖添加標簽。

  2. 迭代視圖中子視圖的for循環。

  3. 刪除時,只需檢查是否具有相同標簽的視圖,然后調用-

    self.removeFromSuperview()

在添加新視圖之前,請先刪除現有視圖。

func internetStatusChanegd() {
    if(isOnline) {
        collectionView.isHidden = true
        for subView in (self.view.subviews)! {
            if (subView.tag == 100) {
                subView.removeFromSuperview() //this will remove already available object form self.view
            }
        }
        if let viewNib = UIView.loadFromNibNamed("CustomView", bundle: Bundle.main) as? CustomView {
            myView = viewNib
            myView!.frame = self.view.bounds
            myView.tag = 100 //add tag when you create object
            self.view.addSubview(myView!)
        }
    }else{
        if let customView = myView{
            customView.removeFromSuperview()
        }
        collectionView.isHidden = false}
    }
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if isOnline{
        collectionView.backgroundView = myView //your custom view whatever you want to show here like : button..
        return 0
    }
    collectionView.backgroundView = nil
    return array.count
}
func internetStatusChanegd(){ collectionView.reloadData() } //it'll handle automatically that view .

嘗試這個

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM