how to add subview at the background - ios

I have a stackview in which there are 3 items vertically aligned. Now I created a Uiview to give it a border and adding that too in stackview to show it as a colored background of with radius corners.
I am successful of creating and attaching a view to the UIStackview. But it seems like it is covering all other arranged subviews of UIStackView. whereas I want to bring other subviews at front. please help me. here is the code below:
extension UIStackView {
override open var backgroundColor: UIColor? {
get {
return super.backgroundColor
}
set {
super.backgroundColor = newValue
let tag = -9999
for view in subviews where view.tag == tag {
view.removeFromSuperview()
}
let subView = UIView()
subView.tag = tag
subView.backgroundColor = newValue
subView.translatesAutoresizingMaskIntoConstraints = false
subView.layer.cornerRadius = 5
subView.layer.masksToBounds = true
subView.layer.borderColor = CommonUtils.hexStringToUIColor(hex: "#C2C2C2").cgColor
subView.layer.borderWidth = 0.35
self.addSubview(subView)
subView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
subView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
subView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
subView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
}
}
}

You can try this
self.insertSubview(subView, at:0)
instead of
self.addSubview(subView)

You can use self.view.bringSubview(toFront: yourView)

Related

How do I align ImageView to the bottom of ScrollView programmatically?

I am trying to align a background image to the bottom of a scroll view that fits the screen, programmatically using Autolayout. Ideally, I want the image to be always aligned at the bottom of the scroll view. When the content of the scroll view goes beyond the screen height or when scroll view content size is less than screen height with scroll view fitting the whole screen.
MyView
class MyView: UIView {
let myScrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.bounces = false
return scrollView
}()
let contentView: UIView = {
let view = UIView()
view.backgroundColor = .red
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let myLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "Hello world"
label.font = UIFont.systemFont(ofSize: 24)
return label
}()
let myImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.image = #imageLiteral(resourceName: "Mask Group 3")
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
setupConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupView() {
backgroundColor = .white
addSubview(myScrollView)
myScrollView.addSubview(contentView)
contentView.addSubview(myLabel)
contentView.addSubview(myImageView)
}
private func setupConstraints() {
myScrollView.topAnchor.constraint(equalTo: topAnchor).isActive = true
myScrollView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
myScrollView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
myScrollView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
contentView.topAnchor.constraint(equalTo: myScrollView.topAnchor).isActive = true
contentView.bottomAnchor.constraint(equalTo: myScrollView.bottomAnchor).isActive = true
contentView.leftAnchor.constraint(equalTo: myScrollView.leftAnchor).isActive = true
contentView.rightAnchor.constraint(equalTo: myScrollView.rightAnchor).isActive = true
contentView.widthAnchor.constraint(equalTo: widthAnchor).isActive = true
// If I am setting this and when the content size go beyond the screen, it does not scroll
// If I don't set this, there is no content size and image view will not position correctly
// contentView.heightAnchor.constraint(equalTo: heightAnchor).isActive = true
myLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 200).isActive = true
myLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
myImageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
myImageView.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
myImageView.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
}
}
MyViewController
import UIKit
class MyViewController: UIViewController {
override func loadView() {
view = MyView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: false)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
Illustration
I have found the solution.
A contentView is needed.
Set the contentView's top, left, bottom, right constraint equal to scrollView edges.
Set the contentView's width equal to view's width anchor
Set the contentView's height greaterThanOrEqualTo view's height anchor
Set the imageView's bottom equal to the bottom anchor of contentView.
For the imageView's top, set the constraint to an element with greaterThanOrEqualTo, to give it a constant gap and avoid overlapping of elements in smaller screens.
It is seems ok:
private func setupConstraints() {
myScrollView.topAnchor.constraint(equalTo: topAnchor).isActive = true
myScrollView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
myScrollView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
myScrollView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
contentView.topAnchor.constraint(equalTo: myScrollView.topAnchor).isActive = true
contentView.bottomAnchor.constraint(equalTo: myScrollView.bottomAnchor).isActive = true
contentView.leftAnchor.constraint(equalTo: myScrollView.leftAnchor).isActive = true
contentView.rightAnchor.constraint(equalTo: myScrollView.rightAnchor).isActive = true
contentView.widthAnchor.constraint(equalTo: widthAnchor).isActive = true
// If I am setting this and when the content size go beyond the screen, it does not scroll
// If I don't set this, there is no content size and image view will not position correctly
contentView.heightAnchor.constraint(equalToConstant: 1400).isActive = true
myLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 200).isActive = true
myLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
myImageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
myImageView.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
myImageView.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
myImageView.heightAnchor.constraint(equalToConstant: 200).isActive = true
}
If think you just forgot to specify image height:
myImageView.heightAnchor.constraint(equalToConstant: 200).isActive = true

Center stack view elements and not fill them

I am using a UIStackView as UITableView's BackGroundView property so when there was an error getting the collection that populates the tableView I can call a function that displays this stack view containing views that show a warning message and a retry button.
I tested doing a similar behaviour in an empty UIViewController so I could center the stackView and its children. The solution worked when I pinned the stack view to the superView's trailing and leading, centered it vertically and set it's top anchor to be greater or equal to the superView's top anchor and similarly it's bottom anchor is greater or equal to the superView's bottom anchor. I have also set the alignment to center and distribution to fill and all seemed to work properly.
Here are some screenshots:
I used this code in a UITableView's extension, but could only reproduce this behaviour. Are there any errors on this code?
func show(error: Bool, withMessage message : String? = nil, andRetryAction retry: (() -> Void)? = nil){
if error{
let iconLabel = UILabel()
iconLabel.GMDIcon = .gmdErrorOutline
iconLabel.textAlignment = .center
iconLabel.numberOfLines = 0
iconLabel.font = iconLabel.font.withSize(50)
iconLabel.textColor = Constants.Colors.ErrorColor
iconLabel.backgroundColor = .blue
let messageLabel = UILabel()
messageLabel.text = message ?? "Ocorreu um erro"
messageLabel.textColor = Constants.Colors.ErrorColor
messageLabel.numberOfLines = 0
messageLabel.textAlignment = .center
messageLabel.font = UIFont(name: "TrebuchetMS", size: 20)
messageLabel.backgroundColor = .green
var views: [UIView] = [iconLabel, messageLabel]
if let retry = retry{
let button = RaisedButton(title: "Tentar novamente")
button.pulseColor = Constants.Colors.PrimaryTextColor
button.backgroundColor = Constants.Colors.PrimaryColor
button.titleColor = .white
button.actionHandle(controlEvents: .touchUpInside, ForAction: retry)
button.contentEdgeInsets = UIEdgeInsetsMake(10,10,10,10)
views.append(button)
}
}else{
self.backgroundView = nil
}
}
let stack = UIStackView()
stack.spacing = 10
stack.axis = .vertical
stack.alignment = .center
stack.distribution = .fill
stack.translatesAutoresizingMaskIntoConstraints = false
for view in views{
view.translatesAutoresizingMaskIntoConstraints = false
stack.addArrangedSubview(view)
}
if self.tableFooterView == nil{
tableFooterView = UIView()
}
self.backgroundView = stack;
if #available(iOS 11, *) {
let guide = self.safeAreaLayoutGuide
stack.topAnchor.constraint(greaterThanOrEqualTo: guide.topAnchor).isActive = true
stack.bottomAnchor.constraint(greaterThanOrEqualTo: guide.bottomAnchor).isActive = true
stack.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
stack.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
stack.centerYAnchor.constraint(equalTo: guide.centerYAnchor).isActive = true
} else {
stack.topAnchor.constraint(greaterThanOrEqualTo: self.topAnchor).isActive = true
stack.bottomAnchor.constraint(greaterThanOrEqualTo: self.bottomAnchor).isActive = true
stack.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
stack.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
stack.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
}
A stack view knows its height if its elements all have an intrinsic size (ie its the sum of their individual heights + the inter item spacing). In this case because you have a 2 y position constraints, you are implying a height, so your constraints are unsatisfiable. The only y axis constraint you need is center vertically. get rid of the top and bottom constraints. The system will then use the intrinsic size to compute the height of the stack view and center it vertically in the background view. Leave your x axis constraints as is.

Why does UIView fill the superView?

I am creating a subview programmatically that I would like to be positioned over a superView, but I do not want it to fill the enter superView.
I have been checking around to see if this question has been asked before but for some reason, I can only find answers to how to fill the entire view.
I would really appreciate it if someone could help critique my code and explain how to position a subView instead of filling the entire superview.
class JobViewController: UIViewController {
var subView : SubView { return self.view as! SubView }
var requested = false
let imageView: UIImageView = {
let iv = UIImageView(image: #imageLiteral(resourceName: "yo"))
iv.contentMode = .scaleAspectFill
iv.isUserInteractionEnabled = true
iv.translatesAutoresizingMaskIntoConstraints = false
return iv
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(imageView)
imageView.fillSuperview()
subView.requestAction = { [ weak self ] in
guard let strongSelf = self else { return }
strongSelf.requested = !strongSelf.requested
if strongSelf.requested {
UIView.animate(withDuration: 0.5, animations: {
strongSelf.subView.Request.setTitle("Requested", for: .normal)
strongSelf.subView.contentView.backgroundColor = UIColor.red.withAlphaComponent(0.5)
})
} else {
UIView.animate(withDuration: 0.5, animations: {
strongSelf.subView.Request.setTitle("Requested", for: .normal)
strongSelf.subView.contentView.backgroundColor = UIColor.blue
})
}
}
}
override func loadView() {
// I know the issue lies here, but how would I go about setting the frame of the subview to just be positioned on top of the mainView?
self.view = SubView(frame: UIScreen.main.bounds)
}
}
I have my subView built in a separate file, I am not sure whether or not I would need its information since It is just what is inside of the subview.
You should add your subView as a subview of self.view and not set it equal your main view. And then set the constraints accordingly.
override func viewDidLoad() {
self.view.addSubview(subView)
subview.translatesAutoresizingMaskIntoConstraint = false
addSubview.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 0).isActive = true
addSubview.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: 0).isActive = true
addSubview.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 0).isActive = true
addSubview.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: 0).isActive = true
}
Regarding your initialisation problem try:
var subView = SubView()
I hope I understood your question correct.

Cannot create UIScrollerView with pure auto layout constraints

I stripped down my code so that its easy to understand.
Say you have a controller and you want to add a simple scroller using pure auto layout.
You can invoke my function tool (provided below) as follows:
// Create scroll view
let strip = addStripCategoryTo(view)
// Attach it to the view, vertically and horizontally
strip.topAnchor.constraintEqualToAnchor(view.topAnchor).active = true
strip.leftAnchor.constraintEqualToAnchor(view.leftAnchor).active = true
// The function
func addStripCategoryTo(parent: UIView) -> UIView {
let h:CGFloat = 128
let w = 2*h/3
let n = 5
let width = w * CGFloat(n)
let height = h
// Scroll view
let scrollview = UIScrollView()
parent.addSubview(scrollview)
scrollview.scrollEnabled = true
scrollview.translatesAutoresizingMaskIntoConstraints = false
scrollview.widthAnchor .constraintEqualToAnchor(parent.widthAnchor).active = true
scrollview.heightAnchor.constraintEqualToConstant(h).active = true
scrollview.layer.borderWidth = 2
scrollview.layer.borderColor = UIColor.greenColor().CGColor
scrollview.backgroundColor = UIColor.brownColor()
// Scroll view content
let contentView = UIView() //frame:CGRect(origin: CGPointZero, size:CGSize(width: width, height: height)))
scrollview.addSubview(contentView)
contentView.backgroundColor = UIColor.redColor()
contentView.layer.borderWidth = 10
contentView.layer.borderColor = UIColor.blueColor().CGColor
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.centerYAnchor.constraintEqualToAnchor(scrollview.centerYAnchor).active = true
contentView.widthAnchor .constraintEqualToConstant(width).active = true
contentView.heightAnchor.constraintEqualToConstant(height).active = true
return scrollview
}
Unfortunately, I cannot scroll it horizontally, see screenshot as follows:
What am I missing?
Your constraints should be like this,
Scrollview - top,bottom,leading,trailing
ContentView - top,bottom,leading,trailing, fixed width, vertically center in container (center y)
and your content view's width should be large than screen width then also you can scroll horizontally
Hope this will help :)
Going to give this a try and answer this, see if it helps.
EDIT
Answering question better, old answer deleted:
Adding these two lines should make to scroll horizontally:
contentView.leadingAnchor.constraintEqualToAnchor(scrollview.leadingAnchor).active = true contentView.trailingAnchor.constraintEqualToAnchor(scrollview.trailingAnchor).active = true
The problem is that without these two constraint, the scrollView doesn't know its contentSize, therefor not scrolling, even though you gave the contentView a specific width. You need to let know the scrollView where does that contentView start and end, and these two constraints will help the scrollView know how big is the contentsView width. If not the scrollView's contentSize is going to stay the same as the device's width, and the contentView is just going to show offscreen since it's width is larger than the device's screen.
Hope this helped better.
Full code of the function
func addStripCategoryTo(parent: UIView)-> UIView {
let h:CGFloat = 128
let w = 2*h/3
let n = 5
let width = w * CGFloat(n)
let height = h
// Scroll view
let scrollview = UIScrollView()
parent.addSubview(scrollview)
scrollview.scrollEnabled = true
scrollview.translatesAutoresizingMaskIntoConstraints = false
scrollview.leadingAnchor.constraintEqualToAnchor(parent.leadingAnchor).active = true
scrollview.trailingAnchor.constraintEqualToAnchor(parent.trailingAnchor).active = true
scrollview.widthAnchor .constraintEqualToAnchor(parent.widthAnchor).active = true
scrollview.heightAnchor.constraintEqualToConstant(h).active = true
scrollview.layer.borderWidth = 2
scrollview.layer.borderColor = UIColor.greenColor().CGColor
scrollview.backgroundColor = UIColor.brownColor()
// Scroll view content
let contentView = UIView() //frame:CGRect(origin: CGPointZero, size:CGSize(width: width, height: height)))
scrollview.addSubview(contentView)
contentView.backgroundColor = UIColor.redColor()
contentView.layer.borderWidth = 10
contentView.layer.borderColor = UIColor.blueColor().CGColor
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.centerYAnchor.constraintEqualToAnchor(scrollview.centerYAnchor).active = true
contentView.leadingAnchor.constraintEqualToAnchor(scrollview.leadingAnchor).active = true
contentView.trailingAnchor.constraintEqualToAnchor(scrollview.trailingAnchor).active = true
contentView.widthAnchor.constraintEqualToConstant(width).active = true
contentView.heightAnchor.constraintEqualToConstant(height).active = true
return scrollview
}
Here is the solution of my issue. I provided a tool function that solve the issue as follow:
func setScrollViewConstraints(scrollView: UIScrollView, contentView:UIView, multiplier m:(width:CGFloat, height:CGFloat)=(1, 1)) {
guard let scrollViewParent = scrollView.superview else {
assert(false, "setScrollViewConstraints() requires the scrollview to have a superview")
return
}
guard let contentViewParent = contentView.superview else {
assert(false, "setScrollViewConstraints() requires the contentView to have a superview")
return
}
guard contentViewParent == scrollView else {
assert(false, "setScrollViewConstraints() requires the contentView to have a superview being the scrollView")
return
}
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.widthAnchor .constraintEqualToAnchor(scrollViewParent.widthAnchor, multiplier: m.width ).active = true
scrollView.heightAnchor .constraintEqualToAnchor(scrollViewParent.heightAnchor, multiplier: m.height).active = true
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.leftAnchor .constraintEqualToAnchor(contentViewParent.leftAnchor ).active = true
contentView.rightAnchor .constraintEqualToAnchor(contentViewParent.rightAnchor ).active = true
contentView.topAnchor .constraintEqualToAnchor(contentViewParent.topAnchor ).active = true
contentView.bottomAnchor.constraintEqualToAnchor(contentViewParent.bottomAnchor ).active = true
/*
// Pre-iOS 9 version
let views = [
"scrollView":scrollview,
"contentView":contentView
]
parent.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[scrollView]|", options:[], metrics: [:], views:views))
parent.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[scrollView]|", options:[], metrics: [:], views:views))
scrollview.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[contentView]|", options:[], metrics: [:], views:views))
scrollview.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[contentView]|", options:[], metrics: [:], views:views))
*/
}
Use it like this for having the scroll view 100% width the super view and 1/4th of its height:
func addStripCategoryTo(parent: UIView) -> UIView {
// Scroll view
let scrollview = UIScrollView()
parent.addSubview(scrollview)
scrollview.backgroundColor = UIColor.brownColor()
scrollview.layer.borderWidth = 2
scrollview.layer.borderColor = UIColor.greenColor().CGColor
// Scroll view content
let contentView = UIImageView()
contentView.image = UIImage(named: "cover-0.jpeg")
scrollview.addSubview(contentView)
contentView.backgroundColor = UIColor.redColor()
contentView.layer.borderWidth = 10
contentView.layer.borderColor = UIColor.blueColor().CGColor
// Apply constraints
setScrollViewConstraints(scrollview, contentView:contentView, multiplier: (1, 0.25))
return scrollview
}

How to change the background color of UIStackView?

I tried to change the UIStackView background from clear to white in Storyboard inspector, but when simulating, the background color of the stack view still has a clear color.
How can I change the background color of a UIStackView?
You can't do this – UIStackView is a non-drawing view, meaning that
drawRect() is never called and its background color is ignored. If you
desperately want a background color, consider placing the stack view
inside another UIView and giving that view a background color.
Reference from HERE.
EDIT:
You can add a subView to UIStackView as mentioned HERE or in this answer (below) and assign a color to it. Check out below extension for that:
extension UIStackView {
func addBackground(color: UIColor) {
let subView = UIView(frame: bounds)
subView.backgroundColor = color
subView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
insertSubview(subView, at: 0)
}
}
And you can use it like:
stackView.addBackground(color: .red)
I do it like this:
#IBDesignable
class StackView: UIStackView {
#IBInspectable private var color: UIColor?
override var backgroundColor: UIColor? {
get { return color }
set {
color = newValue
self.setNeedsLayout() // EDIT 2017-02-03 thank you #BruceLiu
}
}
private lazy var backgroundLayer: CAShapeLayer = {
let layer = CAShapeLayer()
self.layer.insertSublayer(layer, at: 0)
return layer
}()
override func layoutSubviews() {
super.layoutSubviews()
backgroundLayer.path = UIBezierPath(rect: self.bounds).cgPath
backgroundLayer.fillColor = self.backgroundColor?.cgColor
}
}
Works like a charm
UIStackView is a non-rendering element, and as such, it does not get drawn on the screen. This means that changing backgroundColor essentially does nothing. If you want to change the background color, just add a UIView to it as a subview (that is not arranged) like below:
extension UIStackView {
func addBackground(color: UIColor) {
let subview = UIView(frame: bounds)
subview.backgroundColor = color
subview.autoresizingMask = [.flexibleWidth, .flexibleHeight]
insertSubview(subview, at: 0)
}
}
It's worth pointing out that starting with iOS 14, UIStackViews do render background colours. You can either set the background of the UIStackView from the Storyboard with the Background property.
Or in code with:
if #available(iOS 14.0, *) {
stackView.backgroundColor = .green
} else {
// Fallback for older versions of iOS
}
Maybe the easiest, more readable and less hacky way would be to embed the UIStackView into a UIView and set the background color to the view.
And don't forget to configure properly the Auto Layout constraints between those two views… ;-)
Pitiphong is correct, to get a stackview with a background color do something like the following...
let bg = UIView(frame: stackView.bounds)
bg.autoresizingMask = [.flexibleWidth, .flexibleHeight]
bg.backgroundColor = UIColor.red
stackView.insertSubview(bg, at: 0)
This will give you a stackview whose contents will be placed on a red background.
To add padding to the stackview so the contents aren't flush with the edges, add the following in code or on the storyboard...
stackView.isLayoutMarginsRelativeArrangement = true
stackView.layoutMargins = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
TL;DR: The official way to do this is by adding an empty view into stack view using addSubview: method and set the added view background instead.
The explanation: UIStackView is a special UIView subclass that only do the layout not drawing. So many of its properties won't work as usual. And since UIStackView will layout its arranged subviews only, this mean that you can simply add it a UIView with addSubview: method, set its constraints and background color. This is the official way to achieve what you want quoted from WWDC session
This works for me in Swift 3 and iOS 10:
let stackView = UIStackView()
let subView = UIView()
subView.backgroundColor = .red
subView.translatesAutoresizingMaskIntoConstraints = false
stackView.addSubview(subView) // Important: addSubview() not addArrangedSubview()
// use whatever constraint method you like to
// constrain subView to the size of stackView.
subView.topAnchor.constraint(equalTo: stackView.topAnchor).isActive = true
subView.bottomAnchor.constraint(equalTo: stackView.bottomAnchor).isActive = true
subView.leftAnchor.constraint(equalTo: stackView.leftAnchor).isActive = true
subView.rightAnchor.constraint(equalTo: stackView.rightAnchor).isActive = true
// now add your arranged subViews...
stackView.addArrangedSubview(button1)
stackView.addArrangedSubview(button2)
Here is a brief overview for adding a Stack view Background Color.
class RevealViewController: UIViewController {
#IBOutlet private weak var rootStackView: UIStackView!
Creating background view with rounded corners
private lazy var backgroundView: UIView = {
let view = UIView()
view.backgroundColor = .purple
view.layer.cornerRadius = 10.0
return view
}()
To make it appear as the background we add it to the subviews array of the root stack view at index 0. That puts it behind the arranged views of the stack view.
private func pinBackground(_ view: UIView, to stackView: UIStackView) {
view.translatesAutoresizingMaskIntoConstraints = false
stackView.insertSubview(view, at: 0)
view.pin(to: stackView)
}
Add constraints to pin the backgroundView to the edges of the stack view, by using a small extension on UIView.
public extension UIView {
public func pin(to view: UIView) {
NSLayoutConstraint.activate([
leadingAnchor.constraint(equalTo: view.leadingAnchor),
trailingAnchor.constraint(equalTo: view.trailingAnchor),
topAnchor.constraint(equalTo: view.topAnchor),
bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
}
call the pinBackground from viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
pinBackground(backgroundView, to: rootStackView)
}
Reference from: HERE
In iOS10, #Arbitur's answer needs a setNeedsLayout after color is set. This is the change which is needed:
override var backgroundColor: UIColor? {
get { return color }
set {
color = newValue
setNeedsLayout()
}
}
Xamarin, C# version:
var stackView = new UIStackView { Axis = UILayoutConstraintAxis.Vertical };
UIView bg = new UIView(stackView.Bounds);
bg.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
bg.BackgroundColor = UIColor.White;
stackView.AddSubview(bg);
You could make a small extension of UIStackView
extension UIStackView {
func setBackgroundColor(_ color: UIColor) {
let backgroundView = UIView(frame: .zero)
backgroundView.backgroundColor = color
backgroundView.translatesAutoresizingMaskIntoConstraints = false
self.insertSubview(backgroundView, at: 0)
NSLayoutConstraint.activate([
backgroundView.topAnchor.constraint(equalTo: self.topAnchor),
backgroundView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
backgroundView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
backgroundView.trailingAnchor.constraint(equalTo: self.trailingAnchor)
])
}
}
Usage:
yourStackView.setBackgroundColor(.black)
UIStackView *stackView;
UIView *stackBkg = [[UIView alloc] initWithFrame:CGRectZero];
stackBkg.backgroundColor = [UIColor redColor];
[self.view insertSubview:stackBkg belowSubview:stackView];
stackBkg.translatesAutoresizingMaskIntoConstraints = NO;
[[stackBkg.topAnchor constraintEqualToAnchor:stackView.topAnchor] setActive:YES];
[[stackBkg.bottomAnchor constraintEqualToAnchor:stackView.bottomAnchor] setActive:YES];
[[stackBkg.leftAnchor constraintEqualToAnchor:stackView.leftAnchor] setActive:YES];
[[stackBkg.rightAnchor constraintEqualToAnchor:stackView.rightAnchor] setActive:YES];
Subclass UIStackView
class CustomStackView : UIStackView {
private var _bkgColor: UIColor?
override public var backgroundColor: UIColor? {
get { return _bkgColor }
set {
_bkgColor = newValue
setNeedsLayout()
}
}
private lazy var backgroundLayer: CAShapeLayer = {
let layer = CAShapeLayer()
self.layer.insertSublayer(layer, at: 0)
return layer
}()
override public func layoutSubviews() {
super.layoutSubviews()
backgroundLayer.path = UIBezierPath(rect: self.bounds).cgPath
backgroundLayer.fillColor = self.backgroundColor?.cgColor
}
}
Then in your class
yourStackView.backgroundColor = UIColor.lightGray
You can insert a sublayer to StackView, it works to me:
#interface StackView ()
#property (nonatomic, strong, nonnull) CALayer *ly;
#end
#implementation StackView
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
_ly = [CALayer new];
[self.layer addSublayer:_ly];
}
return self;
}
- (void)setBackgroundColor:(UIColor *)backgroundColor {
[super setBackgroundColor:backgroundColor];
self.ly.backgroundColor = backgroundColor.CGColor;
}
- (void)layoutSubviews {
self.ly.frame = self.bounds;
[super layoutSubviews];
}
#end
I am little bit sceptical in Subclassing UI components. This is how I am using it,
struct CustomAttributeNames{
static var _backgroundView = "_backgroundView"
}
extension UIStackView{
var backgroundView:UIView {
get {
if let view = objc_getAssociatedObject(self, &CustomAttributeNames._backgroundView) as? UIView {
return view
}
//Create and add
let view = UIView(frame: .zero)
view.translatesAutoresizingMaskIntoConstraints = false
insertSubview(view, at: 0)
NSLayoutConstraint.activate([
view.topAnchor.constraint(equalTo: self.topAnchor),
view.leadingAnchor.constraint(equalTo: self.leadingAnchor),
view.bottomAnchor.constraint(equalTo: self.bottomAnchor),
view.trailingAnchor.constraint(equalTo: self.trailingAnchor)
])
objc_setAssociatedObject(self,
&CustomAttributeNames._backgroundView,
view,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return view
}
}
}
And this is the usage,
stackView.backgroundView.backgroundColor = .white
stackView.backgroundView.layer.borderWidth = 2.0
stackView.backgroundView.layer.borderColor = UIColor.red.cgColor
stackView.backgroundView.layer.cornerRadius = 4.0
Note: With this approach, if you want to set border, you have to set layoutMargins on the stackView so that the border is visible.
You can't add background to stackview.
But what you can do is adding stackview in a view and then set background of view this will get the job done.
*It will not gonna interrupt the flows of stackview.
Hope this will help.
We can have a custom class StackView like this:
class StackView: UIStackView {
lazy var backgroundView: UIView = {
let otherView = UIView()
addPinedSubview(otherView)
return otherView
}()
}
extension UIView {
func addPinedSubview(_ otherView: UIView) {
addSubview(otherView)
otherView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
otherView.trailingAnchor.constraint(equalTo: trailingAnchor),
otherView.topAnchor.constraint(equalTo: topAnchor),
otherView.heightAnchor.constraint(equalTo: heightAnchor),
otherView.widthAnchor.constraint(equalTo: widthAnchor),
])
}
}
And it can be used like this:
let stackView = StackView()
stackView.backgroundView.backgroundColor = UIColor.lightGray
This is slightly better than adding an extension function func addBackground(color: UIColor) as suggested by others. The background view is lazy so that it won't be created until you actually call stackView.backgroundView.backgroundColor = .... And setting/changing the background color multiple times won't result in multiple subviews being inserted in the stack view.
If you want to control from designer itself , add this extension to stack view
#IBInspectable var customBackgroundColor: UIColor?{
get{
return backgroundColor
}
set{
backgroundColor = newValue
let subview = UIView(frame: bounds)
subview.backgroundColor = newValue
subview.autoresizingMask = [.flexibleWidth, .flexibleHeight]
insertSubview(subview, at: 0)
}
}
There's good answers but i found them not complete so here is my version based on best of them:
/// This extension addes missing background color to stack views on iOS 13 and earlier
extension UIStackView {
private struct CustomAttributeNames {
static var _backgroundView = "_backgroundView"
}
#IBInspectable var customBackgroundColor: UIColor? {
get { backgroundColor }
set { setBackgroundColor(newValue) }
}
var backgroundView: UIView {
if let view = objc_getAssociatedObject(self, &CustomAttributeNames._backgroundView) as? UIView {
return view
}
let view = UIView(frame: bounds)
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
insertSubview(view, at: 0)
objc_setAssociatedObject(self,
&CustomAttributeNames._backgroundView,
view,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return view
}
func setBackgroundColor(_ color: UIColor?) {
backgroundColor = color
backgroundView.backgroundColor = color
}
}
You could do it like this:
stackView.backgroundColor = UIColor.blue
By providing an extension to override the backgroundColor:
extension UIStackView {
override open var backgroundColor: UIColor? {
get {
return super.backgroundColor
}
set {
super.backgroundColor = newValue
let tag = -9999
for view in subviews where view.tag == tag {
view.removeFromSuperview()
}
let subView = UIView()
subView.tag = tag
subView.backgroundColor = newValue
subView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(subView)
subView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
subView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
subView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
subView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
}
}
}
The explanation from the Apple documentation is that a stack view is never itself rendered in iOS 13 - it’s purpose is to manage its arranged subviews:
The UIStackView is a nonrendering subclass of UIView; that is, it does not provide any user interface of its own. Instead, it just manages the position and size of its arranged views. As a result, some properties (like backgroundColor) have no effect on the stack view.
You could fix this by creating an extension just for fixing the background color in iOS 13 or below:
import UIKit
extension UIStackView {
// MARK: Stored properties
private enum Keys {
static var backgroundColorView: UInt8 = 0
}
private var backgroundColorView: UIView? {
get {
objc_getAssociatedObject(self, &Keys.backgroundColorView) as? UIView
}
set {
objc_setAssociatedObject(self, &Keys.backgroundColorView, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
override open var backgroundColor: UIColor? {
didSet {
// UIKit already support setting background color in iOS 14 or above
guard #available(iOS 14.0, *) else {
// fix setting background color directly to stackview by add a background view
if backgroundColorView == nil {
let backgroundColorView = UIView(frame: bounds)
backgroundColorView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
insertSubview(backgroundColorView, at: 0)
self.backgroundColorView = backgroundColorView
}
backgroundColorView?.backgroundColor = backgroundColor
return
}
}
}
}

Resources