How to change the background color of UIStackView?


In iOS, the UIStackView itself doesn't have a background color property. However, you can add a subview to the UIStackView and set its background color. In this example, we will add a stack view with some subviews. After that, we will see how to apply the background color to the stack view.

UIStackView

UIStackView is a container view that arranges its subviews horizontally or vertically. It automatically calculates the size and position of its subviews based on the stack view's axis, distribution, alignment, and spacing properties. You can add subviews to a UIStackView programmatically or in the Interface Builder.

UIStackView has an initializer that takes an array of views as its argument: init(arrangedSubviews:). This initializer is a convenient way to add multiple subviews to a UIStackView at once. This is without having to call addArrangedSubview(_:) for each individual view.

Also, we will use the insertSubview(_:at:) method of UIView that inserts a subview at a specified index in the receiver's list of subviews. When you call this method on a UIStackView, you are adding a new subview to the stack view that is not automatically arranged by the stack view. This means that the new subview will not be managed by the stack view's layout engine, and you will need to set its constraints manually to make it fit within the stack view.

Example

Here's an example of how to use the init(arrangedSubviews:) initializer to create a UIStackView with subviews −

import UIKit
class TestController: UIViewController {
    
   override func viewDidLoad() {
      super.viewDidLoad()
      initialSetup()
   }
    
   private func initialSetup() {
      view.backgroundColor = .white
      navigationItem.title = "UIStackView"
        
      let redView = UIView()
      redView.backgroundColor = .red
        
      let yellowView = UIView()
      yellowView.backgroundColor = .yellow
        
      let greenView = UIView()
      greenView.backgroundColor = .green
        
      let stackView = UIStackView(arrangedSubviews: [redView, yellowView, greenView])
      stackView.axis = .vertical
      stackView.distribution = .fillEqually
      stackView.spacing = 20
      stackView.layer.cornerRadius = 10
      stackView.layer.borderColor = UIColor.black.cgColor
      stackView.layer.borderWidth = 5.0
      stackView.layer.masksToBounds = true
      stackView.translatesAutoresizingMaskIntoConstraints = false
        
      view.addSubview(stackView)
      stackView.heightAnchor.constraint(equalToConstant: 300).isActive = true
      stackView.widthAnchor.constraint(equalToConstant: 250).isActive = true
      stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
      stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
   }
}

Output

In the above example, you can see the output. The stack view is displayed without background color.

Example

Let's see how to apply background color to a stack view. Here is a complete and working example.

import UIKit
class TestController: UIViewController {
    
   override func viewDidLoad() {
      super.viewDidLoad()
      initialSetup()
   }
    
   private func initialSetup() {
      view.backgroundColor = .white
      navigationItem.title = "UIStackView"
        
      let redView = UIView()
      redView.backgroundColor = .red
        
      let yellowView = UIView()
      yellowView.backgroundColor = .yellow
        
      let greenView = UIView()
      greenView.backgroundColor = .green
        
      let stackView = UIStackView(arrangedSubviews: [redView, yellowView, greenView])
      stackView.axis = .vertical
      stackView.distribution = .fillEqually
      stackView.spacing = 20
      stackView.layer.cornerRadius = 10
      stackView.layer.borderColor = UIColor.black.cgColor
      stackView.layer.borderWidth = 5.0
      stackView.layer.masksToBounds = true
      stackView.translatesAutoresizingMaskIntoConstraints = false
        
      view.addSubview(stackView)
      stackView.heightAnchor.constraint(equalToConstant: 300).isActive = true
      stackView.widthAnchor.constraint(equalToConstant: 250).isActive = true
      stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
      stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        
      let backgroundView = UIView()
      backgroundView.backgroundColor = UIColor.blue
      stackView.insertSubview(backgroundView, at: 0)
        
      backgroundView.translatesAutoresizingMaskIntoConstraints = false
      backgroundView.topAnchor.constraint(equalTo: stackView.topAnchor).isActive = true
      backgroundView.bottomAnchor.constraint(equalTo: stackView.bottomAnchor).isActive = true
      backgroundView.leadingAnchor.constraint(equalTo: stackView.leadingAnchor).isActive = true
      backgroundView.trailingAnchor.constraint(equalTo: stackView.trailingAnchor).isActive = true
   }
}

Output

In this completed example, we first create a new UIView instance and set its backgroundColor property to the desired color. Then, we add this UIView as a subview of the UIStackView and set its constraints to make it fill the entire UIStackView.

UIStackView Properties and Methods

UIStackView is a subclass of UIView and it inherits all of its properties and methods. In addition to the inherited properties, UIStackView has its own properties that control the arrangement of its subviews −

  • Axis − This property determines whether the stack view arranges its subviews horizontally or vertically. It is an enum with two possible values: .horizontal and .vertical. The default value is .horizontal.

  • Distribution − This property determines how the stack view distributes its subviews along its axis. It is an enum with five possible values: .fill, .fillEqually, .fillProportionally, .equalSpacing, and .equalCentering. The default value is .fill.

  • Alignment − This property determines how the stack view aligns its subviews perpendicular to its axis. It is an enum with six possible values: .fill, .leading, .trailing, .center, .top, and .bottom. The default value is .fill.

  • Spacing − This property determines the amount of space between adjacent subviews. It is a CGFloat value, with a default value of 0.

UIStackView also has a number of methods for managing its subviews −

  • addArrangedSubview(_:) − This method adds a subview to the end of the stack view's list of arranged subviews. The stack view automatically manages the layout of the subview based on its current settings for axis, distribution, alignment, and spacing.

  • removeArrangedSubview(_:) − This method removes a subview from the stack view's list of arranged subviews. The stack view automatically updates the layout of the remaining subviews.

  • insertArrangedSubview(_:at:) − This method inserts a subview at a specified index in the stack view's list of arranged subviews. The stack view automatically manages the layout of the subview based on its current settings for axis, distribution, alignment, and spacing.

  • setCustomSpacing(_:after:) − This method sets a custom spacing between two adjacent arranged subviews. The first parameter is the spacing value, and the second parameter is the subview that comes before the desired spacing.

  • removeAllArrangedSubviews() − This method removes all the arranged subviews from the stack view.

Conclusion

To summarize, UIStackView is a powerful and flexible container view that allows you to arrange its subviews either horizontally or vertically. Its properties and methods provide a wide range of options for customizing the layout and behavior of the subviews, including setting the axis, distribution, and alignment of the stack view, adjusting the spacing between subviews, and adding or removing subviews.

The arrangedSubviews property provides easy access to the subviews that are being managed by the stack view, while the insertSubview(_:at:) method allows you to add new subviews to the stack view that are not automatically arranged. The init(arrangedSubviews:) initializer provides a convenient way to add multiple subviews to a UIStackView at once and automatically arrange them based on the current settings.

Updated on: 04-May-2023

401 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements