简体   繁体   中英

Removing a UIView and bringing back the UIView in swift

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()
        }
@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)

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)

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)

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)
                ])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM