albertski
albertski

Reputation: 2622

Add more labels to a UIStackView programmatically

I have a UIStackView that contains one Label. I want to display a list of Labels (badges) in the UIStackView. On the first badge, I update the first label and on the other badges, I copy the first badge and add it to the UIStackView with addSubview. It seems to be working but it only shows the last item instead of showing all.

My idea was to have the first Label in the stack view done within the Storyboard so I can easily style it and then clone it in code. Not sure if this is a good approach.

import UIKit

class SessionFullResultViewController: UIViewController {
    
    @IBOutlet weak var badgesStackView: UIStackView!
    @IBOutlet weak var badge1: UILabel!
    
    override func viewDidLoad() {

        ...
        ...

        new_badges.enumerated().forEach { (index, badge) in
            if (index == 0) {
                self.badge1.text = badge.info
            }
            else {
                var newbadge = self.badge1
                newbadge?.text = badge.name
                self.badgesStackView.addSubview(newbadge!)
            }
            
        }
    }

}

Upvotes: 0

Views: 360

Answers (1)

lpizzinidev
lpizzinidev

Reputation: 13289

You need to create a new instance of a label for every text you want to insert, as impression7vx suggested, and also use the addArrangedSubview method

Try to change your code to

new_badges.enumerated().forEach { (index, badge) in
            if (index == 0) {
                self.badge1.text = badge.info
            } else {
                var newbadge = UILabel(frame: badge1.frame)
                newbadge.text = badge.name
                self.badgesStackView.addArrangedSubview(newbadge)
            }

            // Refresh the stack view at the end
            if index == new_badges.count - 1 {
                self.badgesStackView.layoutIfNeeded()
            }
        }

I don't know what kind of layout you want to get, but, with a dynamic list of elements it's usually better to use a UITableView.

Upvotes: 1

Related Questions