Add items in UIStackView programmatically

Jerry PM
2 min readNov 1, 2021

--

Stack view is one of more UI component in xcode

Photo by Iva Rajović on Unsplash

Sometime when you create UI in mobile development is difficult, need to input the correct components so that the development becomes easier.

I often have problems creating difficult IOS UI sometimes combining programmatically and (drag & drop) UI in xib or storyboard,while learn a stack View I’ve become interested, because it makes the UI look more presentable and dynamic.

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

To remove the item from stackview use “removeFromSuperview()” or use this below is code to remove all arrangeSubview on stackview.

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

https://gist.github.com/Deub27/5eadbf1b77ce28abd9b630eadb95c1e2

#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.

This full code how I implement to array data stackView with programatically.

Other example for programatically here : https://gist.github.com/jerrypm/3793f7856f089f40484721620ab08f4e

--

--