Add items in UIStackView programmatically

Photo by Iva Rajović on Unsplash

#Add & remove items to stack view

Dynamic UI is something that should be used in development, with that you can enter dynamic data then the display will adjust, this how to add it.

// add item to stackview
var stackView = UIStackView()
...
let labeNameImage = UILabel()
labeNameImage.font = UIFont.systemFont(ofSize: 12)
labeNameImage.backgroundColor = UIColor.clear
labeNameImage.textColor = .darkGray
labeNameImage.text = "Where Are You"
// use append if there is no data
stackView.append(labeNameImage)
// use arrangedSubviews to adds a view to the end of the array.stackAddPhoto.addArrangedSubview(grup)
extension UIStackView {
func removeAllArrangedSubviews() {
arrangedSubviews.forEach {
self.removeArrangedSubview($0)
NSLayoutConstraint.deactivate($0.constraints)
$0.removeFromSuperview()
}
}
}
// Remove singel item
itemView.removeFromSuperview()
// Remove all items on the stack use extension
stackView.removeAllArrangedSubviews()

#Tap close button in stackView programmatically

This is how to tap close image gesture and delete that image from list, to use that just tag in “imageView.tag” to register index and in this codesender UITapGestureRecognizer use “sender.view.tag” to check your item index after that now reload stackView array data.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store