Constraints failing to add padding - ios

I'm working on a custom control that will eventually be a button. I've successfully built out the design in the interface builder, but when I'm trying to programmatically build the same view, it's not working as expected. I'm attempting to force some padding by setting constants on the constraints that join the labels to their superviews, however, that's not working as expected.
The top button is what I'm expecting (and what I've created in interface builder, do ignore the font differences). The bottom is what I'm getting. There are no errors/warnings being thrown but it's not resizing the superview.
class RoundedButton3: UIView {
var stringLabel: UILabel
var numberLabel: UILabel
var leftBackground: UIView
var rightBackground: UIView
var stackView: UIStackView
override init(frame: CGRect) {
stringLabel = UILabel()
numberLabel = UILabel()
leftBackground = UIView()
rightBackground = UIView()
stackView = UIStackView()
super.init(frame: frame)
self.contentMode = .scaleToFill
self.autoresizingMask = [.flexibleBottomMargin, .flexibleTopMargin, .flexibleLeftMargin, .flexibleRightMargin]
self.translatesAutoresizingMaskIntoConstraints = false
stringLabel.translatesAutoresizingMaskIntoConstraints = false
numberLabel.translatesAutoresizingMaskIntoConstraints = false
leftBackground.translatesAutoresizingMaskIntoConstraints = false
rightBackground.translatesAutoresizingMaskIntoConstraints = false
stackView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(stackView)
leftBackground.addSubview(stringLabel)
rightBackground.addSubview(numberLabel)
stackView.addArrangedSubview(leftBackground)
stackView.addArrangedSubview(rightBackground)
stackView.axis = .horizontal
stackView.alignment = .fill
stackView.distribution = .fill
stringLabel.setContentHuggingPriority(UILayoutPriorityRequired, for: .horizontal)
stringLabel.setContentHuggingPriority(UILayoutPriorityRequired, for: .vertical)
stringLabel.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .horizontal)
stringLabel.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .vertical)
numberLabel.setContentHuggingPriority(UILayoutPriorityRequired, for: .horizontal)
numberLabel.setContentHuggingPriority(UILayoutPriorityRequired, for: .vertical)
numberLabel.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .horizontal)
numberLabel.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .vertical)
self.topAnchor.constraint(equalTo: stackView.topAnchor).isActive = true
self.bottomAnchor.constraint(equalTo: stackView.bottomAnchor).isActive = true
self.rightAnchor.constraint(equalTo: stackView.rightAnchor).isActive = true
self.leftAnchor.constraint(equalTo: stackView.leftAnchor).isActive = true
leftBackground.leftAnchor.constraint(equalTo: stringLabel.leftAnchor, constant: 4).isActive = true
leftBackground.rightAnchor.constraint(equalTo: stringLabel.rightAnchor, constant: 4).isActive = true
leftBackground.topAnchor.constraint(equalTo: stringLabel.topAnchor, constant: 4).isActive = true
leftBackground.bottomAnchor.constraint(equalTo: stringLabel.bottomAnchor, constant: 4).isActive = true
rightBackground.leftAnchor.constraint(equalTo: numberLabel.leftAnchor, constant: 4).isActive = true
rightBackground.rightAnchor.constraint(equalTo: numberLabel.rightAnchor, constant: 4).isActive = true
rightBackground.topAnchor.constraint(equalTo: numberLabel.topAnchor, constant: 4).isActive = true
rightBackground.bottomAnchor.constraint(equalTo: numberLabel.bottomAnchor, constant: 4).isActive = true
stringLabel.text = "RESERVE"
numberLabel.text = "10"
stringLabel.textColor = AppColors.WSF_GREEN
numberLabel.textColor = UIColor.white
rightBackground.backgroundColor = AppColors.WSF_GREEN
leftBackground.backgroundColor = UIColor.white
self.layer.borderColor = AppColors.WSF_GREEN.cgColor
self.layer.borderWidth = 3
self.layer.cornerRadius = 4
self.layer.masksToBounds = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

To define padding you could use the layoutMargins property of the containing view. You can refer to this answer: Adding padding to an UIView.

Related

Set contentMode for Image inside Button in Swift

I am trying to setImage inside my UIButton but the image appears smaller inside the button although there is "free-space" and I also set the contentMode.
Button:
let noteButton: UIButton = {
let v = UIButton()
v.setImage(UIImage(systemName: "pencil"), for: .normal)
v.tintColor = UIColor.white
v.imageView?.contentMode = .scaleAspectFit
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
Constraints:
noteButton.heightAnchor.constraint(equalToConstant: 30).isActive = true
noteButton.widthAnchor.constraint(equalToConstant: 30).isActive = true
noteButton.centerYAnchor.constraint(equalTo: itemView.centerYAnchor).isActive = true
noteButton.leadingAnchor.constraint(equalTo: linkButton.leadingAnchor, constant: 50).isActive = true
Result:
I fixed the issue. I just had to add these to lines:
v.contentHorizontalAlignment = .fill
v.contentVerticalAlignment = .fill

Setting background color for customView has no effect

I have a customView which I display by after a button-tap. My problem is that setting .backgroundColor has no effect and it is just a clear background.
CustomView:
let wishWishView: WishStackView = {
let v = WishStackView()
v.backgroundColor = .cyan
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
AddViewButton:
#objc func addWishButtonTapped(){
self.view.addSubview(self.wishWishView)
wishWishView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
wishWishView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
}
WishWishView is just a simple UIView with a StackView inside of it.
My guess would be that it is a UIStackView, which does not support having a background color.
You can read more about why this happens, and possible workarounds here: https://stackoverflow.com/a/34868367/3992237
Your code is Totally wrong, first you set your view like this:
let wishWishView: UIView = {
let v = UIView()
v.backgroundColor = .cyan
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
now set your stackView, in my example I put in 2 label in vertical axis:
let stackView: UIStackView = {
let label1 = UILabel()
label1.text = "Label 1"
label1.textColor = .red
label1.font = UIFont.systemFont(ofSize: 16)
let label2 = UILabel()
label2.text = "Label 2"
label2.textColor = .black
label2.font = UIFont.systemFont(ofSize: 16)
let sV = UIStackView(arrangedSubviews: [label1, label2])
sV.axis = .vertical
sV.distribution = .fillEqually
sV.translatesAutoresizingMaskIntoConstraints = false
return sV
}()
after that set your button:
let buttonAddView: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Add View", for: .normal)
button.setTitleColor(.white, for: .normal)
button.backgroundColor = .red
button.addTarget(self, action: #selector(addWishButtonTapped), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
in viewDidLoad add button and set constraints
view.addSubview(buttonAddView)
buttonAddView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20).isActive = true
buttonAddView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20).isActive = true
buttonAddView.heightAnchor.constraint(equalToConstant: 50).isActive = true
buttonAddView.widthAnchor.constraint(equalToConstant: 120).isActive = true
now write the function that add the view with stack view inside when the button is tapped with right constraints, in your function you call only the position of the view but not the size of it. Write your function like this:
#objc func addWishButtonTapped(){
view.addSubview(self.wishWishView)
wishWishView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
wishWishView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
wishWishView.heightAnchor.constraint(equalToConstant: 100).isActive = true
wishWishView.widthAnchor.constraint(equalToConstant: 200).isActive = true
wishWishView.addSubview(stackView)
stackView.topAnchor.constraint(equalTo: wishWishView.topAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: wishWishView.bottomAnchor).isActive = true
stackView.leadingAnchor.constraint(equalTo: wishWishView.leadingAnchor, constant: 10).isActive = true
stackView.trailingAnchor.constraint(equalTo: wishWishView.trailingAnchor, constant: -10).isActive = true
}
Now simply change background of the wishWishView to automatically set stackView background, and that's it...

UIStackView distributing with equalCentering

I have created UIStackView programmatically and added 2 views that have 2 child views each. Here are my sample codes:
let sv = UIStackView()
sv.axis = .horizontal
sv.alignment = .center
sv.spacing = Config.Dimensions.horizontalSpacing
sv.distribution = .equalCentering
sv.translatesAutoresizingMaskIntoConstraints = false
let viewCountStudent = UIView()
viewCountStudent.addSubview(studentCount)
viewCountStudent.addSubview(labelStudent)
studentCount.topAnchor.constraint(equalTo: viewCountStudent.topAnchor).isActive = true
studentCount.leftAnchor.constraint(equalTo: viewCountStudent.leftAnchor).isActive = true
studentCount.bottomAnchor.constraint(equalTo: viewCountStudent.bottomAnchor).isActive = true
labelStudent.topAnchor.constraint(equalTo: viewCountStudent.topAnchor).isActive = true
labelStudent.leftAnchor.constraint(equalTo: studentCount.rightAnchor, constant: 8.0).isActive = true
labelStudent.rightAnchor.constraint(equalTo: viewCountStudent.rightAnchor).isActive = true
labelStudent.bottomAnchor.constraint(equalTo: viewCountStudent.bottomAnchor).isActive = true
let viewCountLesson = UIView()
viewCountLesson.addSubview(lessonCount)
viewCountLesson.addSubview(labelLesson)
lessonCount.leftAnchor.constraint(equalTo: viewCountLesson.leftAnchor).isActive = true
lessonCount.topAnchor.constraint(equalTo: viewCountLesson.topAnchor).isActive = true
lessonCount.bottomAnchor.constraint(equalTo: viewCountLesson.bottomAnchor).isActive = true
labelLesson.leftAnchor.constraint(equalTo: lessonCount.rightAnchor, constant: 8.0).isActive = true
labelLesson.rightAnchor.constraint(equalTo: viewCountLesson.rightAnchor).isActive = true
labelLesson.topAnchor.constraint(equalTo: viewCountLesson.topAnchor).isActive = true
labelLesson.bottomAnchor.constraint(equalTo: viewCountLesson.bottomAnchor).isActive = true
sv.addArrangedSubview(viewCountLesson)
sv.addArrangedSubview(viewCountStudent)
sv.topAnchor.constraint(equalTo: divider.bottomAnchor, constant: 8.0).isActive = true
sv.leftAnchor.constraint(equalTo: divider.leftAnchor, constant: 16.0).isActive = true
sv.rightAnchor.constraint(equalTo: divider.rightAnchor, constant: -16.0).isActive = true
sv.bottomAnchor.constraint(equalTo: guide.bottomAnchor, constant: -8.0).isActive = true
addSubview(sv)
The layout it gives is like this:
Above is the horizontal bar and below is the StackView. I wonder why the gap in between 2 views are not equally distributing by stack view. I am trying to center them with spacing distributing equally. Any idea?
This may help you understand...
Each "row" of three green labels is a Horizontal Stack View with Spacing: 8 and Distribution set to:
Fill
Fill Equally
Fill Proportionally
Equal Centering
Equal Spacing
As you can see, with Distribution: Equal Centering, the stack view arranges its subviews so their centers are equally spaced.
What you probably want is equal spacing on the sides and in-between:
To get that layout, use Distribution: Fill and add an empty "spacer" view in the stack, so you have:
spacer1 - viewCountLesson - spacer2 - viewCountStudent - spacer3
then set spacer2 width equal to spacer1 and spacer3 width equal to spacer1.
Here is the code used to create that:
class NewStackViewController: UIViewController {
let studentCount: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .yellow
v.text = "2"
return v
}()
let lessonCount: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .yellow
v.text = "1"
return v
}()
let labelStudent: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .cyan
v.text = "Students"
return v
}()
let labelLesson: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .cyan
v.text = "Lesson"
return v
}()
let divider: UIView = {
let v = UIView()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .gray
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(divider)
NSLayoutConstraint.activate([
divider.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20.0),
divider.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20.0),
divider.heightAnchor.constraint(equalToConstant: 2.0),
divider.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 0.0),
])
let sv = UIStackView()
sv.axis = .horizontal
sv.alignment = .fill
sv.spacing = 0 //Config.Dimensions.horizontalSpacing
sv.distribution = .fill
sv.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(sv)
NSLayoutConstraint.activate([
sv.leadingAnchor.constraint(equalTo: divider.leadingAnchor, constant: 16.0),
sv.trailingAnchor.constraint(equalTo: divider.trailingAnchor, constant: -16.0),
sv.topAnchor.constraint(equalTo: divider.bottomAnchor, constant: 8.0),
])
let viewCountStudent = UIView()
viewCountStudent.addSubview(studentCount)
viewCountStudent.addSubview(labelStudent)
studentCount.topAnchor.constraint(equalTo: viewCountStudent.topAnchor).isActive = true
studentCount.leftAnchor.constraint(equalTo: viewCountStudent.leftAnchor).isActive = true
studentCount.bottomAnchor.constraint(equalTo: viewCountStudent.bottomAnchor).isActive = true
labelStudent.topAnchor.constraint(equalTo: viewCountStudent.topAnchor).isActive = true
labelStudent.leftAnchor.constraint(equalTo: studentCount.rightAnchor, constant: 8.0).isActive = true
labelStudent.rightAnchor.constraint(equalTo: viewCountStudent.rightAnchor).isActive = true
labelStudent.bottomAnchor.constraint(equalTo: viewCountStudent.bottomAnchor).isActive = true
let viewCountLesson = UIView()
viewCountLesson.addSubview(lessonCount)
viewCountLesson.addSubview(labelLesson)
lessonCount.leftAnchor.constraint(equalTo: viewCountLesson.leftAnchor).isActive = true
lessonCount.topAnchor.constraint(equalTo: viewCountLesson.topAnchor).isActive = true
lessonCount.bottomAnchor.constraint(equalTo: viewCountLesson.bottomAnchor).isActive = true
labelLesson.leftAnchor.constraint(equalTo: lessonCount.rightAnchor, constant: 8.0).isActive = true
labelLesson.rightAnchor.constraint(equalTo: viewCountLesson.rightAnchor).isActive = true
labelLesson.topAnchor.constraint(equalTo: viewCountLesson.topAnchor).isActive = true
labelLesson.bottomAnchor.constraint(equalTo: viewCountLesson.bottomAnchor).isActive = true
let sp1 = spacerView()
let sp2 = spacerView()
let sp3 = spacerView()
sv.addArrangedSubview(sp1)
sv.addArrangedSubview(viewCountLesson)
sv.addArrangedSubview(sp2)
sv.addArrangedSubview(viewCountStudent)
sv.addArrangedSubview(sp3)
NSLayoutConstraint.activate([
sp2.widthAnchor.constraint(equalTo: sp1.widthAnchor, multiplier: 1.0),
sp3.widthAnchor.constraint(equalTo: sp1.widthAnchor, multiplier: 1.0),
])
[sp1, sp2, sp3, viewCountLesson, viewCountStudent, studentCount, labelStudent, lessonCount, labelLesson].forEach {
// set borderWidth to 1 to add borders to labels and views so we can see them
$0.layer.borderWidth = 0
$0.layer.borderColor = UIColor.lightGray.cgColor
// un-comment next line to set backgrounds to clear
//$0.backgroundColor = .clear
}
}
func spacerView() -> UIView {
let v = UIView()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .green
return v
}
}

Setting up UI constraint (Image and stackView inside a UIView) programmatically in Swift

I'm trying to build a custom AD when the app opens it pop up some UIViews and image and two buttons then control it from my Firebase, for now I have problem adding the adImage and buttonsStack(contains 2 buttons) inside my backView programmatically and so far nothing works ..
I need the image takes ~ %75 of the backView up and the buttonsStack ~ %25 of the rest
here some code and I have upload it to my GitHub
import UIKit
class ViewController: UIViewController {
let backroundView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .black
view.alpha = 0.5
return view
}()
let backView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .white
view.layer.cornerRadius = 15
return view
}()
let adImage: UIImageView = {
var image = UIImageView()
image.translatesAutoresizingMaskIntoConstraints = false
image.contentMode = .scaleAspectFill
return image
}()
let buttonsStack: UIStackView = {
let stack = UIStackView()
stack.translatesAutoresizingMaskIntoConstraints = false
stack.alignment = UIStackViewAlignment.fill
stack.axis = UILayoutConstraintAxis.vertical
stack.distribution = .equalSpacing
stack.spacing = 8
stack.backgroundColor = UIColor.red
return stack
}()
let actionButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Open", for: .normal)
button.setTitleColor(.white, for: .normal)
button.backgroundColor = UIColor(red: 0, green: 0.60, blue: 1, alpha: 1)
button.layer.cornerRadius = 8
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.textAlignment = .center
return button
}()
let dismessButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("Exit", for: .normal)
button.setTitleColor(.white, for: .normal)
button.backgroundColor = .lightGray
button.layer.cornerRadius = 8
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.textAlignment = .center
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
func setupUI(){
// backroundView
view.addSubview(backroundView)
backroundView.frame = view.frame
// backView
view.addSubview(backView)
backView.topAnchor.constraint(equalTo: view.topAnchor, constant: 80).isActive = true
backView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -50).isActive = true
backView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -25).isActive = true
backView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 25).isActive = true
// adImage
backView.addSubview(adImage)
adImage.image = UIImage(named: "testImage")
adImage.topAnchor.constraint(equalTo: backView.topAnchor).isActive = true
adImage.rightAnchor.constraint(equalTo: backView.rightAnchor).isActive = true
adImage.leftAnchor.constraint(equalTo: backView.leftAnchor).isActive = true
adImage.heightAnchor.constraint(equalTo: backView.heightAnchor, multiplier: 0.50).isActive = true
// buttonsStack
buttonsStack.addArrangedSubview(actionButton)
buttonsStack.addArrangedSubview(dismessButton)
backView.addSubview(buttonsStack)
buttonsStack.topAnchor.constraint(equalTo: backView.topAnchor, constant: 15).isActive = true
buttonsStack.bottomAnchor.constraint(equalTo: backView.bottomAnchor, constant: -15).isActive = true
buttonsStack.rightAnchor.constraint(equalTo: backView.rightAnchor, constant: -15).isActive = true
buttonsStack.leftAnchor.constraint(equalTo: backView.leftAnchor, constant: 15).isActive = true
}
}
For the image to take 0.75 change this
adImage.heightAnchor.constraint(equalTo: backView.heightAnchor, multiplier: 0.50).isActive = true
to
adImage.heightAnchor.constraint(equalTo: backView.heightAnchor, multiplier: 0.75).isActive = true
//
then the buttonStack should goes under it so change this
buttonsStack.topAnchor.constraint(equalTo: backView.topAnchor, constant: 15).isActive = true
to
buttonsStack.topAnchor.constraint(equalTo: adImage.bottomAnchor, constant: 15).isActive = true

View has ambigous layout

Programmatically I'm trying to create a stack view with 5 buttons using auto layout. When i run the project then it run's without showing any error but it is not showing the button stack.
On the other-hand in Debug View Hierarchy, it is showing "View has ambigous layout." What I'm missing here.
class TestView: UIView {
var stackView = UIStackView()
override init(frame: CGRect) {
super.init(frame: frame)
initComponents()
}
func initComponents() {
self.autoresizesSubviews = false
stackView.autoresizesSubviews = false
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.distribution = .equalSpacing
stackView.axis = .horizontal
stackView.alignment = .fill
stackView.contentMode = .scaleToFill
addSubview(stackView)
NSLayoutConstraint.activate([
stackView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
stackView.topAnchor.constraint(equalTo: self.topAnchor),
stackView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
])
for i in 0...4 {
let button = UIButton()
button.titleLabel?.text = "\(i)"
button.translatesAutoresizingMaskIntoConstraints = false
stackView.addSubview(button)
button.heightAnchor.constraint(equalTo: stackView.heightAnchor, multiplier: 1).isActive = true
button.widthAnchor.constraint(equalTo: button.heightAnchor, multiplier: 1).isActive = true
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}}
In ViewController.swift file
let frame = CGRect(x: 0, y: 0, width: 200, height: 30)
let test = TestView.init(frame: frame)
self.view.addSubview(test)
I had to change a few things to make this work:
Use button.setTitle(_:for:) to set the title of the buttons.
Set a color for your text with button.setTitleColor(_:for:).
Set a background color for your buttons.
Add the buttons to the stackView with stackView.addArrangedSubview(button).
Also, you might want to move the frame down a bit. It's in the upper left corner which puts it over top of the status bar and behind the notch of the iPhone X.
for i in 0...4 {
let button = UIButton()
button.setTitle("\(i)", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
// Set these colors to whatever you like
button.setTitleColor(.black, for: .normal)
button.backgroundColor = .red
stackView.addArrangedSubview(button)
button.heightAnchor.constraint(equalTo: stackView.heightAnchor, multiplier: 1).isActive = true
button.widthAnchor.constraint(equalTo: button.heightAnchor, multiplier: 1).isActive = true
}

Resources