Swift 4, UIStackViews Not Displaying - swift

Strange bug(s) I'm encountering..
This code:
// Label 1
let textLabel1 = UILabel()
textLabel1.backgroundColor = UIColor.yellow
textLabel1.text = "Label1"
textLabel1.textAlignment = .center
// Label 2
let textLabel2 = UILabel()
textLabel2.backgroundColor = UIColor.blue
textLabel2.text = "Label2"
textLabel2.textAlignment = .center
// Label 3
let textLabel3 = UILabel()
textLabel3.backgroundColor = UIColor.green
textLabel3.text = "Label3"
textLabel3.textAlignment = .center
let h1StackView = UIStackView()
h1StackView.axis = UILayoutConstraintAxis.horizontal
h1StackView.distribution = .fillEqually
h1StackView.alignment = UIStackViewAlignment.fill
h1StackView.spacing = 0
h1StackView.addArrangedSubview(textLabel3)
h1StackView.addArrangedSubview(textLabel2)
self.view.addSubview(h1StackView)
let h2StackView = UIStackView()
h2StackView.axis = UILayoutConstraintAxis.horizontal
h2StackView.distribution = .fillEqually
h2StackView.alignment = UIStackViewAlignment.fill
h2StackView.spacing = 0
h2StackView.addArrangedSubview(textLabel3)
h2StackView.addArrangedSubview(textLabel1)
self.view.addSubview(h2StackView)
//Stack View
let stackView = UIStackView(frame: CGRect(x: 0, y: pos.VERT_STACK_Y, width: pos.SCREEN_WIDTH, height: pos.VERT_STACK_HEIGHT))
stackView.axis = UILayoutConstraintAxis.vertical
stackView.distribution = .fillEqually
stackView.alignment = UIStackViewAlignment.fill
stackView.spacing = 0
stackView.addArrangedSubview(h1StackView)
stackView.addArrangedSubview(h2StackView)
self.view.addSubview(stackView)
Gives this view:
Buggy Image 1
This is close to correct, but wrong because I'm not expecting that big blue bar, rather, half blue - half green.
It gets a little weirder though for me...
If I change just one character in the code (textLabel2 to textLabel1):
(This):
let h1StackView = UIStackView()
h1StackView.axis = UILayoutConstraintAxis.horizontal
h1StackView.distribution = .fillEqually
h1StackView.alignment = UIStackViewAlignment.fill
h1StackView.spacing = 0
h1StackView.addArrangedSubview(textLabel3)
h1StackView.addArrangedSubview(textLabel2)
self.view.addSubview(h1StackView)
(To this):
let h1StackView = UIStackView()
h1StackView.axis = UILayoutConstraintAxis.horizontal
h1StackView.distribution = .fillEqually
h1StackView.alignment = UIStackViewAlignment.fill
h1StackView.spacing = 0
h1StackView.addArrangedSubview(textLabel3)
h1StackView.addArrangedSubview(textLabel1)
self.view.addSubview(h1StackView)
Then I get this view:
Buggy Image 2
It seems there are two problems and I can't quite fix either.. any ideas? I'm hoping this is a me problem and not a Swift/Xcode one.
(P.S. Sorry not enough rep to embed images)

The main problem resides in the logic of that single instance can only be inside one view at a time , so first when you repeated adding lbl3 to both the horizontal stackViews , it appeared at the last one (stack2) , same when you repeated adding 1,3 , they only show inside horizontal stack 2 , so to repeat you have to create another object , also if you decided to create a main stack to hold the 2 horizontal stacks then comment these 2 lines
self.view.addSubview(h1StackView)
self.view.addSubview(h2StackView)

arrangedSubViews is a subset of all subviews —
From the docs on UIView
A parent view may contain any number of subviews but each subview has only one superview.
This is expanded on in addSubView(_:)
Views can have only one superview. If view already has a superview and that view is not the receiver, this method removes the previous superview before making the receiver its new superview.
So when you add textLabel3 to h2StackView in this line:
h2StackView.addArrangedSubview(textLabel3)
You're implicitly removing it from h1StackView

Related

sendSubviewToBack is not working when an UIView is added to a custom UILabel

I am iterating values and add them to a container UIView.
for value in bla {
// Create a new label
let labelHashtag = UILabelBadge()
labelHashtag.backgroundColor = .white
labelHashtag.frame.size.width = labelHashtag.intrinsicContentSize.width + tagPadding
labelHashtag.frame.size.height = tagHeight
labelHashtag.layer.cornerRadius = labelHashtag.layer.frame.size.height / 2
labelHashtag.topInset = 2
labelHashtag.bottomInset = 2
labelHashtag.rightInset = 6
labelHashtag.leftInset = 6
labelHashtag.textAlignment = .center
// !!! Here I am trying to add an UIView and send it back !!!
let bla = UIView()
bla.frame = labelHashtag.bounds
bla.backgroundColor = .red
labelHashtag.addSubview(bla)
labelHashtag.sendSubviewToBack(bla)
Container.addSubview(labelHashtag)
}
It also does not work when I use insertSubview at: 0. It will stay on the top of my UILabel.
How can I add an UIView and send it back?
When you add subview on UILabel means that UILabel is the root and all subviews will on the front of root view.
From your question, there are two approaches to achieve that.
First one, create a root UIView and add your UILabel and UIView into
for value in bla {
let rootUIView = UIView()
// Create a new label
let labelHashtag = UILabelBadge()
labelHashtag.backgroundColor = .white
labelHashtag.frame.size.width = labelHashtag.intrinsicContentSize.width + tagPadding
labelHashtag.frame.size.height = tagHeight
labelHashtag.layer.cornerRadius = labelHashtag.layer.frame.size.height / 2
labelHashtag.topInset = 2
labelHashtag.bottomInset = 2
labelHashtag.rightInset = 6
labelHashtag.leftInset = 6
labelHashtag.textAlignment = .center
// !!! Here I am trying to add an UIView and send it back !!!
let backgroundView = UIView()
backgroundView.frame = labelHashtag.bounds
backgroundView.backgroundColor = .red
rootUIView.addSubview(labelHashtag)
rootUIView.addSubview(backgroundView)
rootUIView.sendSubviewToBack(backgroundView)
Container.addSubview(rootUIView)
}
Second one, make your UIView as a root and add your custom UILabel into it
for value in bla {
// Create a new label
let labelHashtag = UILabelBadge()
labelHashtag.backgroundColor = .white
labelHashtag.frame.size.width = labelHashtag.intrinsicContentSize.width + tagPadding
labelHashtag.frame.size.height = tagHeight
labelHashtag.layer.cornerRadius = labelHashtag.layer.frame.size.height / 2
labelHashtag.topInset = 2
labelHashtag.bottomInset = 2
labelHashtag.rightInset = 6
labelHashtag.leftInset = 6
labelHashtag.textAlignment = .center
// !!! Here I am trying to add an UIView and send it back !!!
let backgroundView = UIView()
backgroundView.frame = labelHashtag.bounds
backgroundView.backgroundColor = .red
backgroundView.addSubview(labelHashtag)
Container.addSubview(backgroundView)
}

Adding labels and textviews in a stack view programmatically in swift

How can I do to have a title, followed by a few lines of text, followed by a title again and again few lines of text constrained in the middle of a view controller programmatically?
My goal is to have bolded for the titles, and it would be nice to have the textview lines incremented also.
My idea was to create 2 labels, and 2 textviews. And adding those to a textview in this order: label1, t1, label2, t2.
But it doesn't seem to work. I try to avoid defining the same textviews and labels many times. textviews add up if I copy its definition twice but not for labels (maybe it is view related?)
I tried with UIbuttons and it worked.
This is what I tried so far:
import UIKit
class HowToSetupProIGVC: UIViewController {
deinit {print("deinit")}
let textView: UITextView = {
let textView = UITextView()
textView.backgroundColor = .blue //bkgdColor
textView.textAlignment = .left
//textView.frame = CGRect(x: 5, y: 5, width: 5, height: 5)
textView.tintColor = .black
textView.translatesAutoresizingMaskIntoConstraints = false //enable autolayout
textView.heightAnchor.constraint(equalToConstant: 100).isActive = true
textView.widthAnchor.constraint(equalToConstant: 300).isActive = true
return textView
}()
let label: UILabel = {
let l = UILabel(frame:CGRect.zero)
//l.frame = CGRect(x: 5, y: 5, width: 5, height: 5)
l.backgroundColor = .green //bkgdColor
l.font = UIFont.preferredFont(forTextStyle: .headline)
l.translatesAutoresizingMaskIntoConstraints = false //enable autolayout
l.heightAnchor.constraint(equalToConstant: 22).isActive = true
l.widthAnchor.constraint(equalToConstant: 300).isActive = true
return l
}()
override func viewDidLoad() {
super.viewDidLoad()
self.modalUI(arrowButton: false)
self.view.backgroundColor = bkgdColor
customStackHTSProIG ()
}
}
extension HowToSetupProIGVC {
func customStackHTSProIG () {
let label1 = label
let label2 = label
let t1 = textView
let t2 = textView
label1.text = "Title1:"
label2.text = "title2:"
t1.text = """
1. On your profile tap menu
2. Tap settings
3. Tap accounts
4. Tap set up professional account
"""
t2.text = """
1. On your profile tap "Edit profile"
2. Link your created page to your account
"""
//StackView
let stackHTS = UIStackView()
stackHTS.axis = NSLayoutConstraint.Axis.vertical
stackHTS.distribution = .fillEqually
stackHTS.alignment = .center
stackHTS.spacing = 5
stackHTS.backgroundColor = .red
//Add StackView + elements
stackHTS.addArrangedSubview(label1)
stackHTS.addArrangedSubview(t1)
stackHTS.addArrangedSubview(label2)
stackHTS.addArrangedSubview(t2)
self.view.addSubview(stackHTS)
//Constraints StackView
stackHTS.translatesAutoresizingMaskIntoConstraints = false
stackHTS.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
stackHTS.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
//stackHTS.heightAnchor.constraint(equalToConstant: 88).isActive = true
}
}
UILabel & UITextView are both UIKit classes written in Objective-C. They are reference types, NOT value types.
When you write following -
let label1 = label
let label2 = label
let t1 = textView
let t2 = textView
Both label1 & label2 are pointing to the one & same instance of UILabel. So is the case for t1 & t2 as well.
When you add them like this -
//Add StackView + elements
stackHTS.addArrangedSubview(label1)
stackHTS.addArrangedSubview(t1)
stackHTS.addArrangedSubview(label2)
stackHTS.addArrangedSubview(t2)
You expect 2 labels and 2 textViews to be added to the StackView. You are adding only 1 label and 1 textView though.
You expect to see all of following -
label1.text = "Title1:"
label2.text = "title2:"
t1.text = """
1. On your profile tap menu
2. Tap settings
3. Tap accounts
4. Tap set up professional account
"""
t2.text = """
1. On your profile tap "Edit profile"
2. Link your created page to your account
"""
However you are only seeing following -
label2.text = "title2:"
t2.text = """
1. On your profile tap "Edit profile"
2. Link your created page to your account
"""
Solutions -
Create two separate instances of UITextView & UILabel like you have already done for the first two and Add these new instances to stack view as well.
Use one UILabel and remove everything else. Use NSAttributedString API to stylize your text as you want for different sections / paragraphs and assign it to UILabel.attributedText.

Why doesn't my UILabel in a nested view receive touch events / How can I test the Responder Chain?

I have found lots of similar questions about not receiving touch events and I understand that in some cases, writing a custom hitTest function may be required - but I also read that the responder chain will traverse views and viewControllers that are in the hierarchy - and I don't understand why a custom hitTest would be required for my implementation.
I'm looking for an explanation and/or a link to a document that explains how to test the responder chain. This problem is occurring in Xcode 10.2.1.
My scenario (I am not using Storyboard):
I have a mainViewController, that provides a full screen view with an ImageView and a few Labels. I have attached TapGestureRecognizers to the ImageView and one of the labels - and they both work properly.
When I tap the label, I add a child viewController and it's view as a subview to the mainViewController. The view is constrained to cover only the right-half of the screen.
The child viewController contains a vertical stack view that contains 3 arrangedSubviews.
Each arrangedSubview contains a Label and a horizontal StackView.
The horizontal stackView's each contain a View with a Label as a subview.
The Label in the subview sets it's isUserInteractionEnabled flag to True and adds a TapGestureRecognizer.
These are the only objects in the child ViewController that have 'isUserInteractionEnabled' set.
The Label's are nested fairly deep, but since this is otherwise a direct parent/child hierarchy (as opposed to the 2 views belonging to a NavigationController), I would expect the Label's to be in the normal responder chain and function properly. Do the Stack View's change that behavior? Do I need to explicitly set the 'isUserInteractionEnabled' value to False on some of the views? Is there way I can add logging to the ResponderChain so I can see which views it checked and find out where it is being blocked?
After reading this StackOverflow post I tried adding my gesture recognizers in viewDidLayoutSubviews() instead of what's shown below - but they still do not receive tap events.
Thank you in advance to any who can offer advice or help.
Here is the code for the label that is not responding to my tap events and the tap event it should call:
func makeColorItem(colorName:String, bgColor:UIColor, fgColor:UIColor) -> UIView {
let colorNumber:Int = colorLabelDict.count
let colorView:UIView = {
let v = UIView()
v.tag = 700 + colorNumber
v.backgroundColor = .clear
v.contentMode = .center
return v
}()
self.view.addSubview(colorView)
let tapColorGR:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapColor))
let colorChoice: UILabel = {
let l = UILabel()
l.tag = 700 + colorNumber
l.isUserInteractionEnabled = true
l.addGestureRecognizer(tapColorGR)
l.text = colorName
l.textAlignment = .center
l.textColor = fgColor
l.backgroundColor = bgColor
l.font = UIFont.systemFont(ofSize: 24, weight: .bold)
l.layer.borderColor = fgColor.cgColor
l.layer.borderWidth = 1
l.layer.cornerRadius = 20
l.layer.masksToBounds = true
l.adjustsFontSizeToFitWidth = true
l.translatesAutoresizingMaskIntoConstraints = false
l.widthAnchor.constraint(equalToConstant: 100)
return l
}()
colorView.addSubview(colorChoice)
colorChoice.centerXAnchor.constraint(equalTo: colorView.centerXAnchor).isActive = true
colorChoice.centerYAnchor.constraint(equalTo: colorView.centerYAnchor).isActive = true
colorChoice.heightAnchor.constraint(equalToConstant: 50).isActive = true
colorChoice.widthAnchor.constraint(equalToConstant: 100).isActive = true
colorLabelDict[colorNumber] = colorChoice
return colorView
}
#objc func tapColor(sender:UITapGestureRecognizer) {
print("A Color was tapped...with tag:\(sender.view?.tag ?? -1)")
if let cn = sender.view?.tag {
colorNumber = cn
let v = colorLabelDict[cn]
if let l = (v?.subviews.first as? UILabel) {
print("The \(l.text) label was tapped.")
}
}
}
It looks like the main reason you're not getting a tap recognized is because you are adding a UILabel as a subview of a UIView, but you're not giving that UIView any constraints. So the view ends up with a width and height of Zero, and the label exists outside the bounds of the view.
Without seeing all of your code, it doesn't look like you need the extra view holding the label.
Take a look at this... it will add a vertical stack view to the main view - centered X and Y - and add "colorChoice" labels to the stack view:
class TestViewController: UIViewController {
let stack: UIStackView = {
let v = UIStackView()
v.axis = .vertical
v.spacing = 4
return v
}()
var colorLabelDict: [Int: UIView] = [:]
override func viewDidLoad() {
super.viewDidLoad()
let v1 = makeColorLabel(colorName: "red", bgColor: .red, fgColor: .white)
let v2 = makeColorLabel(colorName: "green", bgColor: .green, fgColor: .black)
let v3 = makeColorLabel(colorName: "blue", bgColor: .blue, fgColor: .white)
[v1, v2, v3].forEach {
stack.addArrangedSubview($0)
}
stack.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stack)
NSLayoutConstraint.activate([
stack.centerXAnchor.constraint(equalTo: view.centerXAnchor),
stack.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
}
func makeColorLabel(colorName:String, bgColor:UIColor, fgColor:UIColor) -> UILabel {
let colorNumber:Int = colorLabelDict.count
// create tap gesture recognizer
let tapColorGR:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapColor))
let colorChoice: UILabel = {
let l = UILabel()
l.tag = 700 + colorNumber
l.addGestureRecognizer(tapColorGR)
l.text = colorName
l.textAlignment = .center
l.textColor = fgColor
l.backgroundColor = bgColor
l.font = UIFont.systemFont(ofSize: 24, weight: .bold)
l.layer.borderColor = fgColor.cgColor
l.layer.borderWidth = 1
l.layer.cornerRadius = 20
l.layer.masksToBounds = true
l.adjustsFontSizeToFitWidth = true
l.translatesAutoresizingMaskIntoConstraints = false
// default .isUserInteractionEnabled for UILabel is false, so enable it
l.isUserInteractionEnabled = true
return l
}()
NSLayoutConstraint.activate([
// label height: 50, width: 100
colorChoice.heightAnchor.constraint(equalToConstant: 50),
colorChoice.widthAnchor.constraint(equalToConstant: 100),
])
// assign reference to this label in colorLabelDict dictionary
colorLabelDict[colorNumber] = colorChoice
// return newly created label
return colorChoice
}
#objc func tapColor(sender:UITapGestureRecognizer) {
print("A Color was tapped...with tag:\(sender.view?.tag ?? -1)")
// unwrap the view that was tapped, make sure it's a UILabel
guard let tappedView = sender.view as? UILabel else {
return
}
let cn = tappedView.tag
let colorNumber = cn
print("The \(tappedView.text ?? "No text") label was tapped.")
}
}
Result of running that:
Those are 3 UILabels, and tapping each will trigger the tapColor() func, printing this to the debug console:
A Color was tapped...with tag:700
The red label was tapped.
A Color was tapped...with tag:701
The green label was tapped.
A Color was tapped...with tag:702
The blue label was tapped.

Size (width/height) constraints on diff elements in UIStackView overriding each others' constraints

I am currently placing a UIImageView with a fixed width and height constraint of 20 and a UIView underneath that UIImageView. But the UIView has a width of 20, same as the UIImageView but when I add a width constraint of 10 to the UIView the UIImageView becomes 10x10... Below is my implementation: -
guard let superview = superview else { return }
verticalStack = UIStackView()
verticalStack?.translatesAutoresizingMaskIntoConstraints = false
verticalStack?.isLayoutMarginsRelativeArrangement = true
verticalStack?.axis = .vertical
verticalStack?.backgroundColor = UIColor.green
verticalStack?.spacing = 5.0
brightnessIcon = UIImageView(image: UIImage(named: "brightness.png"))
brightnessIcon?.contentMode = .scaleAspectFit
brightnessIcon?.widthAnchor.constraint(equalToConstant: 20.0).isActive = true
brightnessIcon?.heightAnchor.constraint(equalToConstant: 20.0).isActive = true
verticalStack?.addArrangedSubview(brightnessIcon!)
brightnessIndicator = UIView()
brightnessIndicator?.backgroundColor = UIColor.red
brightnessIndicator?.widthAnchor.constraint(equalToConstant: 5.0).isActive = true
verticalStack?.addArrangedSubview(brightnessIndicator!)
Below is the image before I add the width constraint to the brightnessIndicator (UIView):-
After adding width constraint to the brightnessIndicator:-
You have to change your stackView's alignment. By default this is set to fill which tries to layout the arranged subviews to fill the opposite axis of your stackView (in your case they will be filled horizontally).
Try setting the alignment to leading, trailing, or centered (you have to check for yourself what fits your needs). As these alignment options don't force the arranged subviews to resize.
You need to set distribution and alignment of your stackView
verticalStack?.translatesAutoresizingMaskIntoConstraints = false
verticalStack?.isLayoutMarginsRelativeArrangement = true
verticalStack?.axis = .vertical
verticalStack?.alignment = .center
verticalStack?.distribution = .fillProportionally

Swift and Visual Format Language (VFL) not happy with vertical and horizontal layout

I am trying to make a UIView that consist of 4 element:
1 x UIView
3 x UIScrollView
Layout setup
The 4 subviews works perfectly individually, however the VFL for this view has turned out to be difficult. The views are configured like this:
let frame0View = UIView()
frame0View.translatesAutoresizingMaskIntoConstraints = false
frame0View.backgroundColor = .yellow
frame0View.frame = CGRect(x: 0, y: 0, width: 80, height: 100)
let frame1ScrollView = UIScrollView()
frame1ScrollView.backgroundColor = .cyan
frame1ScrollView.translatesAutoresizingMaskIntoConstraints = false
frame1ScrollView.contentSize = frame1View.bounds.size
and the same for frame2ScrollView and 3
My expectation is the a VFL setup like this for the “superview” should work:
let mainHorizontalVFL1 = "H:|[FRAME0(80)]-[FRAME1SCROLL(>=200)]-(>=0#500)-|"
let mainHorizontalVFL2 = "H:|[FRAME2SCROLL(80)]-[FRAME3SCROLL(>=200)]-(>=0#500)-|"
let mainVerticalVFL = "V:|[FRAME0(60)]-[FRAME2SCROLL(\(numberOfPlayers*90))]-(>=1#500)-|"
However this does not work (both FRAME1SCROLL and FRAME3SCROLL is not visible at all). By accident I got the below setup to work (with the auto layout complaining about "Unable to simultaneously satisfy constraints” as expected)
let mainHorizontalVFL1 = "H:|[FRAME0(80)]-[FRAME1SCROLL(>=200)]-(>=0#500)-|"
let mainHorizontalVFL2 = "H:|[FRAME2SCROLL(80)]-[FRAME3SCROLL(>=200)]-(>=0#500)-|"
let mainVerticalVFL = "V:|[FRAME0(60)]-[FRAME1SCROLL(60)]-[FRAME2SCROLL(\(numberOfPlayers*90))]-[FRAME3SCROLL(\(numberOfPlayers*90))]-(>=0#500)-|"
This setup works for now, but it is kind of annoying that I am not able to use the expected setup. Anyone has any idea what to look for to fix this?