简体   繁体   中英

Adding UIView back to View

I have multiple subviews in my main view controller, I am using a delete button to remove one subview at a time. I am trying to allow the user to bring back the view that was deleted, but the view is not coming back. Any thoughts? In Swift.

@IBOutlet var tornView: UIView!
var deleted = 1 

// Delete Button
    @IBAction func deleteViewButton(sender: AnyObject) {
        if deleted == 1 {
            tornView.removeFromSuperview()
            deleted = 2
        }
    }

// Brings View to Screen 
@IBAction func showTornAnnotation(sender: AnyObject) {
        if toggleState == 1 {
            firstSlider.hidden = false
            tornView.hidden = false
            toggleState = 2
            if deleted == 2 {
                view.addSubview(tornView)
            }
        }
        else {
            firstSlider.hidden = true
            tornView.hidden = true
            toggleState = 1
        }
    }

If you want IBOutlet to be removed from the superView and get it added back then you should always use strong references to your IBOutlet . Being said you should also keep the position of the removed view so that you can use it when you are ready to add it back.

Edit: Sample code

@IBOutlet var customView: UIView!
var customViewFrame: CGRect?

override func viewDidLoad() {
    super.viewDidLoad()
    customView.backgroundColor = UIColor.blueColor()
}
@IBAction func remove(sender: AnyObject) {
    customViewFrame = customView.frame
    customView.removeFromSuperview()
}

@IBAction func add(sender: AnyObject) {
    if let rect = customViewFrame {
        customView = UIView.init(frame: rect)
        customView.backgroundColor = UIColor.blueColor()

        view.addSubview(customView)
        view.bringSubviewToFront(customView)
    }
}

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