Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding views dynamically to UIStackview

I'm trying to add views(or buttons) to UIStackView dynamically.

At first, the UIStackView has no arranged views (vertically), and after getting from some http response, several views(buttons) are added to UIStackView. UIStackView is also autolayout to hold a specific area. I've tried to find dynamic adding example, but failed.

Anyone can show me the examples of adding view onto UIStackView dynamically?

like image 587
GT Kim Avatar asked Dec 23 '22 05:12

GT Kim


1 Answers

It may help you. Please follow this points:

  • Add UIScrollView to your UIViewController in storyboard or XIB.
  • Initiate an NSMutableArray name it arrViews gets server response and adds view in the array.
  • Initialise UIStackViewpass arrView array in the init method.
  • After that UIStackView will be added subview of UIScrollView.
  • Add constraint programmatically to UIStackView. That's it.

    if let response = self.serverResponse {
        if let body = response.responseBody {
    
            if let view = body.views {
                arrViews =  createSubViews(view)
            }
    
        }
    }
    
    let stackView = UIStackView(arrangedSubviews: arrViews)
    stackView.translatesAutoresizingMaskIntoConstraints = false
    stackView.axis = .vertical
    stackView.spacing = 16
    stackView.distribution = .fill
    self.scrollView.addSubview(stackView)
    
    //constraints
    
    let leading = NSLayoutConstraint(item: stackView, attribute: .leading, relatedBy: .equal, toItem: self.scrollView, attribute: .leading, multiplier: 1.0, constant: 0)
    self.scrollView.addConstraint(leading)
    let trailing = NSLayoutConstraint(item: stackView, attribute: .trailing, relatedBy: .equal, toItem: self.scrollView, attribute: .trailing, multiplier: 1.0, constant: 0)
    self.scrollView.addConstraint(trailing)
    let top = NSLayoutConstraint(item: stackView, attribute: .top, relatedBy: .equal, toItem: self.scrollView, attribute: .top, multiplier: 1.0, constant: 0)
    self.scrollView.addConstraint(top)
    
    let bottom = NSLayoutConstraint(item: stackView, attribute: .bottom, relatedBy: .equal, toItem: self.scrollView, attribute: .bottom, multiplier: 1.0, constant: 0)
    self.scrollView.addConstraint(bottom)
    
    let equalWidth = NSLayoutConstraint(item: stackView, attribute: .width, relatedBy: .equal, toItem: self.scrollView, attribute: .width, multiplier: 1.0, constant: 0)
    
    self.scrollView.addConstraint(equalWidth)
    
    
    leading.isActive = true
    trailing.isActive = true
    top.isActive = true
    bottom.isActive = true
    equalWidth.isActive = true
    

Hope it will help you. Happy coding :)

like image 190
iamVishal16 Avatar answered Dec 29 '22 11:12

iamVishal16