That was a long chapter, and I hope you learned a lot. But you deserve a break, so I have some good news: it's trivial to remove views from a UIStackView. Heck, at its simplest it's just a matter of telling removeArrangedSubview()
which view you don’t want then removing that view from its superview – the others are automatically resized and re-arranged to fill the space.
However, using removeArrangedSubview()
doesn’t remove the view altogether – it keeps the view in memory, which is helpful if you plan to re-add it later on because you can avoid recreating it. Here, though, we actually want to remove the web view and destroy it entirely, and that can be done with a call to removeFromSuperview()
instead.
In this particular project, we need to do a little more:
setDefaultTitle()
to reset the user interface.We already pointed the delete button at a method called deleteWebView()
, so all you need to do is plug this in. I've added comments to make sure it's all clear:
@objc func deleteWebView() {
// safely unwrap our webview
if let webView = activeWebView {
if let index = stackView.arrangedSubviews.firstIndex(of: webView) {
// We found the webview – remove it from the stack view and destroy it
webView.removeFromSuperview()
if stackView.arrangedSubviews.count == 0 {
// go back to our default UI
setDefaultTitle()
} else {
// convert the Index value into an integer
var currentIndex = Int(index)
// if that was the last web view in the stack, go back one
if currentIndex == stackView.arrangedSubviews.count {
currentIndex = stackView.arrangedSubviews.count - 1
}
// find the web view at the new index and select it
if let newSelectedWebView = stackView.arrangedSubviews[currentIndex] as? WKWebView {
selectWebView(newSelectedWebView)
}
}
}
}
}
So, although the act of removing a view from a UIStackView
is just a matter of calling either removeArrangedSubview()
or removeFromSuperview()
depending on whether you want to use it again, we need to do a little more to make sure the user interface updates correctly.
The last thing we're going to do is talk about multitasking on iPad, and add a few user interface clean ups to make the project complete…
TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.