Reputation: 285
I am using a UIView not a view controller/ I am removing the view once the delete button is clicked. I am trying to make the view come back when a user wants the view back. example : myView.removeFromSuperview() Is there anyway to bring the view back? In swift thank you guys!
@IBOutlet weak var brokeView: UIView!
@IBOutlet weak var deleteButton: UIButton!
@IBAction func deleteViewButton(sender: AnyObject) {
if brokeView != nil {
brokeView.removeFromSuperview()
}
Upvotes: 7
Views: 3729
Reputation: 362
If you want to use IBoutlet
you need to remove weak
from your IBoutlet
after you remove weak
you remove and add the view again to your view but you need to set the constraints programmatically to view.
Example:
// removed 'weak' reference
@IBOutlet var mButton: UIButton!
... other functionality
// remove from superview
mButton.removeFromSuperview()
// add again to view
view.addSubview(mButton)
// set re-set constraints
NSLayoutConstraint.activate([
mButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
mButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -40)
])
Upvotes: 0
Reputation: 42977
@IBOutlet weak var brokeView: UIView!
you already have a reference to the view brokeView
which you are going to remove and add again, but its weak
so it will be deallocated once it is removed from superView
. Since you need this brokeView
to add back make it strong
.
@IBOutlet var brokeView: UIView!
Now you can add it back like
view.addSubview(brokeView)
Upvotes: 18
Reputation: 5060
if you removing it from superview, you can add it again, but you should not make that view as nil other wise you will have to create new one.Removing from superview only remove view from parent view.
subview.removeFromSuperview() // remove from parent view
parentView.addSubview(subview) //adding again on it parent view
Create a View: This sample, it depends on your view which init method, you have created, used that one.
MyCustomView *customView = MyCustomView(frame: CGRectZero(top: 0, left: 0, width: 200, height: 50)
self.view.addSubview(customView)
Upvotes: 0
Reputation: 680
No, there is no way to get it back unless you initialise it again. You can hide the view and unhide it.
viewToBeHidden.hidden = true
//when you want to make it reappear unhide it.
viewToBeHidden.hidden = false
Or like @rmaddy suggested keep the reference.
var myView = UIView()
myView.removeFromSuperview
//then just add it back.
self.view.addSubView(myView)
Upvotes: 0