Remove all subviews from a Stack View

Asked

Viewed 39 times

0

At a certain time of my application I consume an API and add buttons in a Stack View.

The name of my Stack view is "viewPossibleAnswer".

for answer in newListsResponses {
 let newButton = UIButton()
 newButton.setTitle(answer.sentence, for: .normal)
 newButton.setTitleColor(UIColor.white, for: .normal)
 self.viewPossibleAnswer.addSubview(newButton)
}

This way is inserting the buttons very well but I need to remove all the buttons inside the Stack View at a certain time.

I did the following function to try to remove all buttons inside the Stack View.

for itemSubView in self.viewPossibleAnswer.arrangedSubviews{
 self.viewPossibleAnswer.removeArrangedSubview(itemSubView)
}

2 answers

1

Ricardo, you can also use the syntax shorthand then to accomplish the same:

viewPossibleAnswer.subviews.forEach({ $0.removeFromSuperview() })

In the example, I suggested using the method forEach, which accepts a parameter: a closure to be executed for each element of the sequence/collection.

The shorthand mentioned is nothing more than a language shortcut, so that the code is more concise, if so desired. Basically, it is equivalent to the following:

viewPossibleAnswer.subviews.forEach({ itemSubView in

  itemSubView.removeFromSuperview()

})

It is up to you whether or not to use the syntax shorthand, usually good for simple/short cases like this, as it makes the code more readable (no breaks/indentations).

If you want to understand better, follow the reference (section Shorthand Argument Names): https://docs.swift.org/swift-book/LanguageGuide/Closures.html.

0

I was wrong since I am adding "subviews" the correct function is to access the value of the "subviews" of my Stack View so I changed my function.

for itemSubView in self.viewPossibleAnswer.subviews{
 itemSubView.removeFromSuperview()
}

I hope this can help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.