TableView not appearing after setting the constraints programmatically - ios

I have a UITableView in my storyboard. I am trying to setup constraints for it in my view controller. After running the application it's not showing up at all. it's only working when i don't run the constraints. here are my constraints.
func tableviewsConstraints(){
homeTableView.translatesAutoresizingMaskIntoConstraints = false
homeTableView.layer.cornerRadius = 10
homeTableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 20).isActive = true
homeTableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -20).isActive = true
homeTableView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 50).isActive = true
homeTableView.heightAnchor.constraint(equalToConstant: homeTableView.rowHeight * 3).isActive = true
self.view.addSubview(homeTableView)
}
override func viewDidLoad() {
super.viewDidLoad()
tableviewsConstraints()

Add the homeTableView as the view's subview before adding the constraints to it. And use a constant value when setting the height of tableView, i.e.
func tableviewsConstraints(){
self.view.addSubview(homeTableView) //here....
homeTableView.layer.cornerRadius = 10
homeTableView.translatesAutoresizingMaskIntoConstraints = false
homeTableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 20).isActive = true
homeTableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -20).isActive = true
homeTableView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 50).isActive = true
let rowHeight: CGFloat = 100.0 //here....
homeTableView.heightAnchor.constraint(equalToConstant: rowHeight * 3).isActive = true
}
Change the rowHeight value as per your requirement.

Don't you have the outlet of the table view if you have it in the storyboard? Then why you need to subview? If you're creating table view programmatically then follow this.

Related

Swift Programmatic Constraint not working

I am trying to create a uiview that has a segment control inside. I want to be able to add this uiview to my viewcontroller's view. the segment control should be right on top of my tableview. but everytime i setup the constraints i keep getting this error
"Thread 1: Exception: "Unable to activate constraint with anchors <NSLayoutYAxisAnchor:0x282ee24c0 "UIView:0x119d3a610.bottom"> and <NSLayoutYAxisAnchor:0x282ee2500 "UITableView:0x11a014a00.top"> because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal."" I tried working around by adding the subview first and what not but it's not working. here's my code if anyone can help me.
func configureTableView(){
setupSegmentControl()
view.addSubview(tableView)
setTableViewDelegates()
tableView.rowHeight = 50
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
self.tableView.topAnchor.constraint(equalToSystemSpacingBelow: self.view.topAnchor, multiplier: 20).isActive = true
tableView.register(UINib(nibName: "CustomCellNSB2", bundle: nil), forCellReuseIdentifier: "CustomCellNSB2")
}
func setTableViewDelegates(){
tableView.delegate = self
tableView.dataSource = self
}
func setupSegmentControl(){
var headerView = UIView()
var importanceSegmentControl = CustomSegmentControl()
headerView.addSubview(importanceSegmentControl)
self.view.addSubview(headerView)
importanceSegmentControl.addTarget(self, action: #selector(indexChanged(control:)),for: UIControl.Event.valueChanged)
headerView.translatesAutoresizingMaskIntoConstraints = false
headerView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 20).isActive = true
headerView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -20).isActive = true
headerView.bottomAnchor.constraint(equalTo: self.tableView.topAnchor, constant: 20).isActive = true
headerView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 10).isActive = true
importanceSegmentControl.translatesAutoresizingMaskIntoConstraints = false
importanceSegmentControl.leadingAnchor.constraint(equalTo: headerView.leadingAnchor, constant: 20).isActive = true
importanceSegmentControl.trailingAnchor.constraint(equalTo: headerView.trailingAnchor, constant: -20).isActive = true
importanceSegmentControl.bottomAnchor.constraint(equalTo: headerView.topAnchor, constant: 20).isActive = true
importanceSegmentControl.topAnchor.constraint(equalTo: headerView.topAnchor, constant: 10).isActive = true
}
The tableView and importanceSegmentControl doesn't have any common ancestor at the time of adding the constraint to the importanceSegmentControl. So to fix the issue just switch the order of execution:
func configureTableView(){
view.addSubview(tableView)
setupSegmentControl()
//...
}

How to programmatically place two labels in center side by side with spacing using auto layout in ios swift?

I am very new to swift and IOS and I want to place two labels side by side horizontally center programmatically. Below is my code
let secondLabel : UILabel = {
let label = UILabel()
label.text = "1234"
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.blue
return label
}()
let thirdLabel : UILabel = {
let label = UILabel()
label.text = "5678"
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.red
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupLayout()
}
private func setupLayout(){
view.addSubview(secondLabel)
//secondLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
secondLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
secondLabel.widthAnchor.constraint(equalToConstant: 100).isActive = true
secondLabel.heightAnchor.constraint(equalToConstant: 100).isActive = true
view.addSubview(thirdLabel)
//thirdLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
thirdLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
thirdLabel.widthAnchor.constraint(equalToConstant: 100).isActive = true
thirdLabel.heightAnchor.constraint(equalToConstant: 100).isActive = true
self.view.addConstraint(NSLayoutConstraint(
item: thirdLabel,
attribute: .left,
relatedBy: .equal,
toItem: secondLabel,
attribute: .right,
multiplier: 1.0,
constant: 10
))
}
But this is how it looks now
Please help me to move the labels to the center
You can use UIStackView to solve your problem. Please update the following code in your setupLayout method.
private func setupLayout(){
let stackview = UIStackView()
stackview.axis = .horizontal
stackview.spacing = 10
stackview.translatesAutoresizingMaskIntoConstraints = false
stackview.addArrangedSubview(secondLabel)
secondLabel.widthAnchor.constraint(equalToConstant: 100).isActive = true
secondLabel.heightAnchor.constraint(equalToConstant: 100).isActive = true
stackview.addArrangedSubview(thirdLabel)
thirdLabel.widthAnchor.constraint(equalToConstant: 100).isActive = true
thirdLabel.heightAnchor.constraint(equalToConstant: 100).isActive = true
self.view.addSubview(stackview)
stackview.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
stackview.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
}
Output:-
Well UIStackView will be the best option and #manikandan has answered properly.
But if you are not a big fan of UIStackView, you can achieve it using UIView too. A bit more lines of code and it will work.
private func setupLayout() {
let sampleBackgroundView = UIView()
sampleBackgroundView.translatesAutoresizingMaskIntoConstraints = false
sampleBackgroundView.addSubview(secondLabel)
secondLabel.topAnchor.constraint(equalTo: secondLabel.superview!.topAnchor).isActive = true
secondLabel.bottomAnchor.constraint(equalTo: secondLabel.superview!.bottomAnchor).isActive = true
secondLabel.leadingAnchor.constraint(equalTo: secondLabel.superview!.leadingAnchor, constant: 10).isActive = true
secondLabel.widthAnchor.constraint(equalToConstant: 100).isActive = true
secondLabel.heightAnchor.constraint(equalToConstant: 100).isActive = true
sampleBackgroundView.addSubview(thirdLabel)
thirdLabel.topAnchor.constraint(equalTo: secondLabel.superview!.topAnchor).isActive = true
thirdLabel.bottomAnchor.constraint(equalTo: secondLabel.superview!.bottomAnchor).isActive = true
thirdLabel.trailingAnchor.constraint(equalTo: secondLabel.superview!.trailingAnchor, constant: 10).isActive = true
thirdLabel.widthAnchor.constraint(equalToConstant: 100).isActive = true
thirdLabel.heightAnchor.constraint(equalToConstant: 100).isActive = true
sampleBackgroundView.addConstraint(NSLayoutConstraint(
item: thirdLabel,
attribute: .left,
relatedBy: .equal,
toItem: secondLabel,
attribute: .right,
multiplier: 1.0,
constant: 10
))
view.addSubview(sampleBackgroundView)
sampleBackgroundView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
sampleBackgroundView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
Please go through these solutions and you will have a better idea to implement constraints programmatically:
How to add constraints programmatically using Swift
https://theswiftdev.com/2018/06/14/mastering-ios-auto-layout-anchors-programmatically-from-swift/
https://theswiftdev.com/2017/10/31/ios-auto-layout-tutorial-programmatically/
While a UIStackView is one way to go (and easier many times), there are also times that you want to do what you are trying. Truth is, you're almost there.
private func setupLayout(){
view.addSubview(secondLabel)
secondLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: -55).isActive = true
secondLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
secondLabel.widthAnchor.constraint(equalToConstant: 100).isActive = true
secondLabel.heightAnchor.constraint(equalToConstant: 100).isActive = true
view.addSubview(thirdLabel)
thirdLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 55).isActive = true
thirdLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
thirdLabel.widthAnchor.constraint(equalToConstant: 100).isActive = true
thirdLabel.heightAnchor.constraint(equalToConstant: 100).isActive = true
}
Basically, it looks like you have two 100x100 UILabels that you want 10 points apart. So:
Get rid of that last constraint.
Comment back in those two centerXAnchor constraints. This will move both labels on top of each other, centered horizontally.
Now you just need to add a constant property to each constraint. A negative value move to the left and a positive value moves to the right. Since your widths are 100, a value of 50should make the labels be right next to each. For 10 points in between them, make it 55.
There're two options for you to work on that (or maybe more).
Create Additional containerView(UIView) to addSubView your 2 labels. Then centerYAnchor that containerView to your baseView.
Using UIStackView. Add those 2 labels into your Horizontal StackView and centerYAnchor to your baseView
Simple explanation hopes this helps.
Using a container view (either UIView, or UIStackView) might be the best approach, as it would allow you to easier build other UI components around the group of two labels. But if you don't need this flexibility, or want to avoid using an extra view, you can achieve the desired layout quite nicely via layout anchors:
NSLayoutConstraint.activate([
// set the size
secondLabel.widthAnchor.constraint(equalToConstant: 100),
secondLabel.heightAnchor.constraint(equalToConstant: 100),
// center vertically in the parent view
secondLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
// align to the left of the parent view center
secondLabel.rightAnchor.constraint(equalTo: view.centerXAnchor, constant: -5),
// set the size
thirdLabel.widthAnchor.constraint(equalToConstant: 100),
thirdLabel.heightAnchor.constraint(equalToConstant: 100),
// center vertically in the parent view
thirdLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
// align to the right of the parent view center
thirdLabel.leftAnchor.constraint(equalTo: view.centerXAnchor, constant: 5)
])
The spacing between the two is automatically achieved via the offsets from the X center.
As a general note, Apple recommends activating constraints in batches, by using activate(), for performance reasons:
The effect of this method is the same as setting the isActive property of each constraint to true. Typically, using this method is more efficient than activating each constraint individually.

How to set constraint relationship to view, not subviews programmatically?

I am trying to setup a couple of views programmatically. On my main view I add two subviews, one anchored to the top and one to the bottom:
//Button View
view.addSubview(buttonsLabel)
buttonsLabel.translatesAutoresizingMaskIntoConstraints = false
buttonsLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
buttonsLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
buttonsLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20).isActive = true
buttonsLabel.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5, constant: -20).isActive = true
//Calculator View
calcLabel.layer.cornerRadius = 25
view.addSubview(calcLabel)
calcLabel.translatesAutoresizingMaskIntoConstraints = false
calcLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
calcLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
calcLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 40).isActive = true
//calcLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20).isActive = true
calcLabel.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5, constant: -40).isActive = true
This works fine, both views are 50% of the frame height (minus the constants) and both are shown (one at the top, one at the bottom). But when I try to add a third view, which is 75% of the frames height and which should be placed on top of the other two views, the layout is destroyed and everything is moved almost outside of the frame.
I am trying to anchor the third view to the bottom again:
thirdView.layer.cornerRadius = 25
view.addSubview(thirdView)
thirdView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
thirdView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
thirdView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
thirdView.heightAnchor.constraint(equalTo: view.heightAnchor,multiplier: 0.75).isActive = true
This is how everything should look like (left the two views, right the third view on top:
Am I doing the anchors and constraints right (or whats abetter way) and how to add the constraint for the third view, so that it is 75% of the frames height and placed like in the image on top of everything.
Your code looks good the problem is else where, check the view hierarchy in the debugger to see which constraint(s) failed, perhaps you forgot translatesAutoresizingMaskIntoConstraints as beyowulf commented. you should be using constants as well, this makes code much more maintainable.
here is my implementation:
import UIKit
class ViewController: UIViewController {
//MARK: - SubViews
let topHalfView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = UIColor.gray
return view
}()
let bottomHalfView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = UIColor.gray
return view
}()
let threeQuarterView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = UIColor.black
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//add, layout subviews with 9+ constraints
setupViews()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupViews() {
self.view.addSubview(topHalfView)
self.view.addSubview(bottomHalfView)
self.view.addSubview(threeQuarterView)
let guide = self.view.safeAreaLayoutGuide
let spacing:CGFloat = 12
let viewHeight = self.view.frame.height - spacing
topHalfView.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
topHalfView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: spacing).isActive = true
topHalfView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -spacing).isActive = true
topHalfView.heightAnchor.constraint(equalToConstant: viewHeight * 0.5).isActive = true
bottomHalfView.topAnchor.constraint(equalTo: topHalfView.bottomAnchor, constant: spacing).isActive = true
bottomHalfView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: spacing).isActive = true
bottomHalfView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -spacing).isActive = true
bottomHalfView.heightAnchor.constraint(equalToConstant: viewHeight * 0.5).isActive = true
threeQuarterView.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
threeQuarterView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: spacing).isActive = true
threeQuarterView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -spacing).isActive = true
threeQuarterView.heightAnchor.constraint(equalToConstant: self.view.frame.height * 0.75).isActive = true
}
}
The View hierarchy:

Frame from iOs 9 constraints

I am having trouble with getting the actual width out of my view. I have added my UIView() as "progressBar" to the controller's view but I need to get the width in order to execute some other code.
Is there any possible way I can get the object's width out of those constraints?
Thank you for helping! Appreciate it.
progressBar.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(progressBar)
progressBar.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
progressBar.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -430).isActive = true
progressBar.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -40).isActive = true
progressBar.heightAnchor.constraint(equalToConstant: 4).isActive = true

UIScrollView nested subviews not displayed using Auto Layout

I am trying to generate views displayed in a UIScrollView based on structured (XML) data at runtime. I generate all the views I need and add them to my scrollview afterwards, using Auto Layout to let the scrollview calculate its contentSize. Everything worked fine as long as I was only using UILabels and a custom UIImageView subclass, but now I want to add a nested view containing another view and a label to represent text with a vertical line on the left side.
The general layout code I'm using to add all generated views to the scrollview is as follows:
var previousAnchor = scrollView.topAnchor
views.forEach { (view) in
scrollView.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.topAnchor.constraint(equalTo: previousAnchor,
constant: UI.defaultPadding).isActive = true
view.leadingAnchor.constraint(equalTo: self.view.leadingAnchor,
constant: UI.smallPadding).isActive = true
view.trailingAnchor.constraint(equalTo: self.view.trailingAnchor,
constant: -UI.smallPadding).isActive = true
previousAnchor = view.bottomAnchor
}
scrollView.bottomAnchor.constraint(equalTo: previousAnchor,
constant: UI.defaultPadding).isActive = true
And the layout code for my nested subview looks like this (it's a UIView subclass):
addSubview(label)
addSubview(line)
line.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10).isActive = true
line.topAnchor.constraint(equalTo: topAnchor).isActive = true
line.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
line.widthAnchor.constraint(equalToConstant: 2).isActive = true
line.trailingAnchor.constraint(equalTo: label.leadingAnchor).isActive = true
line.backgroundColor = UIColor.green
label.topAnchor.constraint(equalTo: topAnchor).isActive = true
label.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
label.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
label.numberOfLines = 0
label.text = "Here's to the crazy ones. The misfits. The rebels. The troublemakers."
If I use this code, I cannot see this view in my scrollview at all and the scrollview has a warning of ambiguous content size attached to it in the Debug View Hierarchy view. This is somewhat irritating, as using labels without being nested in a view like this does work like a charm. So I started playing around and what really puzzles me is that if I use the following code I can see the view itself (as I gave it a gray background color), but still can't see line and/or label, as both seem have a frame of (0,0,0,0) upon inspection:
addSubview(label)
addSubview(line)
line.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10).isActive = true
line.topAnchor.constraint(equalTo: topAnchor, constant: 10).isActive = true
line.widthAnchor.constraint(equalToConstant: 20).isActive = true
line.heightAnchor.constraint(equalToConstant: 20).isActive = true
line.trailingAnchor.constraint(equalTo: label.leadingAnchor).isActive = true
line.backgroundColor = UIColor.green
label.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
label.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
heightAnchor.constraint(equalToConstant: 100).isActive = true
heightAnchor.constraint(equalTo: label.heightAnchor).isActive = true
label.numberOfLines = 0
label.text = "Here's to the crazy ones. The misfits. The rebels. The troublemakers."
What am I missing? I also tried putting all my views into a container view instead of using them as subviews of the scrollview directly, but this did not help with my nested view and brought up other problems.

Resources