Search code examples
iosswift3addsubview

Add Removed Subview Swift 3 iOS


In a self.view there is a subview(tempView) which I am removing from superview but when I am trying to add that back it is not showing in the view. while checking the frame I found that their frame is correct but the view is not visible. Below is the code for removing my view from superview and adding it back.

if(self.view.subviews.contains(self.tempView))
{
    self.tempView.removeFromSuperview()
}
else
{
    self.view.addSubview(self.tempView)
    self.view.bringSubview(toFront:self.tempView)
    self.view.setNeedsLayout()
    self.view.layoutIfNeeded()
}

Solution

  • Try set translatesAutoresizingMaskIntoConstraints=true

    if(self.view.subviews.contains(self.tempView))
    {
        self.tempView.removeFromSuperview()
    }
    else
    {
        self.tempView.translatesAutoresizingMaskIntoConstraints=true
        self.view.addSubview(self.tempView)
        self.view.bringSubview(toFront:self.tempView)
    }