Chris D. Chris D. - 3 months ago 18x
iOS Question

UIStackView not appearing in Container View

Can someone please explain to me why I cannot see this StackView show up in its container?

This is what it looks like now:
enter image description here

This is what I want it to look like, ignore the cells, I just need to figure out why the Edit button, search bar and Sort button are not showing.

enter image description here

Here is the code I used to setup the views and their contents:

// Container
let barViewFrame = CGRectMake(0, 0, view.frame.width, 44)
let barViewContainer = UIView(frame: barViewFrame)
barViewContainer.backgroundColor = UIColor(red: 231/255, green: 231/255, blue: 231/255, alpha: 1.0)
tableView.tableHeaderView = barViewContainer

// Edit Button
let editButton = UIButton(type: .System)
editButton.bounds = CGRectMake(0, 0, 44, 44)
editButton.setTitle("Edit", forState: .Normal)

// Search Bar
let searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: 50, height: 44))
searchBar.placeholder = "Search"
searchBar.searchBarStyle = .Prominent
searchBar.barTintColor = UIColor(red: 231/255, green: 231/255, blue: 231/255, alpha: 1.0)

// Sort Button
let sortButtton = UIButton(type: .Custom)
sortButtton.bounds = CGRectMake(0, 0, 44, 44)
sortButtton.setImage(UIImage(named: "Sort"), forState: .Normal)

// Stackview
let stackViewH = UIStackView(arrangedSubviews: [editButton, searchBar, sortButtton])
stackViewH.axis = .Horizontal
stackViewH.alignment = .Center
stackViewH.spacing = 8




When you add views programmatically, iOS assumes that you want to layout those views using frames. To make this work with auto layout, behinds the scenes it adds constraints so the view will appear according to its frame. But, you are adding constraints that you want the auto layout engine to use rather than the ones it would like to create. So to tell auto layout not to generate those constraints you can set the translatesAutoresizingMaskIntoConstraints to false for the views on which you don't want this to occur.

In your case:

stackViewH.translatesAutoresizingMaskIntoConstraints = false