Swift - constraint issues with UIScrollView (programmatically) - ios

I recently added a scrollview to my viewcontroller. However, this caused my layout to mess up completely.
Here's an image below.
(I gave the UIScrollView a temporary red background, to display, that it's clearly taking the full screen)
now. I have a bunch of things in this view. But to keep it simple I will focus on the top blue bar, which in my app is called "topBar"
First of, I define it in my class.
var topBar = UIView()
I remove the auto sizing, give it a color and add it to my scrollview.
//----------------- topBar ---------------//
topBar.setTranslatesAutoresizingMaskIntoConstraints(false)
topBar.backgroundColor = UIColor.formulaBlueColor()
self.scrollView.addSubview(topBar)
add it to my viewsDictionary:
var viewsDictionary = [ "topBar":topBar]
add the height to my metricsDictionary:
let metricsDictionary = ["topBarHeight":6]
set the height in a sizing constraint.
//sizing constraints
self.scrollView.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"V:[topBar(topBarHeight)]", options: NSLayoutFormatOptions(0), metrics: metricsDictionary, views: viewsDictionary))
And finally the part that doesn't work. I /attempt/ to make it the full width of "scrollView"
// Horizontal Constraints
self.scrollView.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"H:|[topBar]|", options: nil, metrics: nil, views: viewsDictionary))
and my vertical constraint to put it at the top.
// Vertical Constraints
self.scrollView.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat(
"V:|[topBar]", options: nil, metrics: nil, views: viewsDictionary))
Now as for my scrollview, (the one that's probably causing my layout headaches)
It's set up as follows:
as the very first thing in the class:
let scrollView = UIScrollView(frame: UIScreen.mainScreen().bounds)
first thing in my viewDidLoad()
self.view.addSubview(scrollView)
scrollView.setTranslatesAutoresizingMaskIntoConstraints(false)
scrollView.scrollEnabled = true
and lastly my viewDidLayoutSubviews.
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.frame = view.bounds
scrollView.contentSize = CGSize(width:2000, height: 5678)
}
^ The width of the contentSize will be changed to the width of the screen (I only want vertical scrolling). But right now that's a minor issue compared to the layout problems I'm having
Any help as to why everything is squeezed together would be greatly appreciated!

I managed to fix it doing the following.
Defining my contentsize in viewDidLayoutSubviews
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.frame = view.bounds
scrollView.contentSize = CGSize(width:self.view.bounds.width, height: 5678)
}
and instead of making the view equal to a scrollview, I had to make it a subview of it.
I also had to make a subview of the scrollview, for all my content to work with constraints properly.
self.view.addSubview(scrollView)
scrollView.translatesAutoresizingMaskIntoConstraints = false
contentView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(contentView)
and all my other objects was made subviews of the "contentView" and not the scrollview.

Related

UIScrollView does not fit with constraints

I'd like to use a scrollView to move the nested view content up when the keyboard appears. (Maybe you know a better solution ?)
So, I put a UIScrollView into my UIViewController and a UIImageView into my UIScrollView. The problem is my UIScrollView is as large as my image size despite constraints.
I put the following constraints :
scrollView.addConstraintsWithFormat(format: "H:|[v0]|", views: backgroundImage)
scrollView.addConstraintsWithFormat(format: "V:|[v0]|", views: backgroundImage)
self.view.addConstraintsWithFormat(format: "H:|[v0]|", views: scrollView)
self.view.addConstraintsWithFormat(format: "V:|[v0]|", views: scrollView)
Someone have a solution ?
This is my full UIViewController code :
import UIKit
class HomeViewController: UIViewController {
let scrollView: UIScrollView = {
let screenSize = UIScreen.main.bounds
let scrollView = UIScrollView()
scrollView.backgroundColor = .red
scrollView.contentSize = CGSize(width: screenSize.width, height: screenSize.height)
return scrollView
}()
let backgroundImage: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "BACKGROUND_ASIA")
imageView.alpha = 0.5
return imageView
}()
override func viewDidLoad() {
setupHomeView()
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func setupHomeView() {
self.view.backgroundColor = UIColor.black
self.view.addSubview(scrollView)
self.view.addConstraintsWithFormat(format: "H:|[v0]|", views: scrollView)
self.view.addConstraintsWithFormat(format: "V:|[v0]|", views: scrollView)
scrollView.addSubview(backgroundImage)
scrollView.addConstraintsWithFormat(format: "H:|[v0]|", views: backgroundImage)
scrollView.addConstraintsWithFormat(format: "V:|[v0]|", views: backgroundImage)
}
}
extension UIView {
func addConstraintsWithFormat(format: String, views: UIView...) {
var viewsDictionary = [String: UIView]()
for (index, view) in views.enumerated() {
let key = "v\(index)"
viewsDictionary[key] = view
view.translatesAutoresizingMaskIntoConstraints = false
}
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary))
}
}
You should call super first in viewDidLoad.
You should read up on how scrollViews work.
Here's what you need:
The ScrollView needs constraints for left/right/top/bottom.
This will determine the size of the presentable portion of the scrollview. This is the part that you would resize when the keyboard shows.
Then, you need to set the size of the ScrollView's content. This is the content that can be scrolled. You will need to manually set the size of your imageView, or setup equality between your imageView and views that exist outside of your scrollview. (eg imageView.width == view.width).
Hope this points in the right direction. You might want to consider using Interface Builder to set this up so you can see all the constraints and get warning when things aren't set up properly.
Thanks for your answer PEEJWEEJ, but I found another alternative to my problem. I used the NotificationCenter to notify keyboard opening and I made a view.animate() to scroll my view. By this way I avoid to use a scrollView or a tableView.

Horizontal auto-layout constraint

In a subclass of UITableViewCell, I am trying to use auto layout.
Here is what I want to do :
Here is my code which doesn't work : only one view is shown
import Foundation
class CustomCell: UITableViewCell {
func configureCell() {
backgroundColor = UIColor.yellowColor()
let redColorView = UIView()
redColorView.backgroundColor = UIColor.redColor()
redColorView.translatesAutoresizingMaskIntoConstraints = false
let blueColorView = UIView()
blueColorView.backgroundColor = UIColor.blueColor()
blueColorView.translatesAutoresizingMaskIntoConstraints = false
addSubview(blueColorView)
addSubview(redColorView)
let viewsDictionary = ["blue":blueColorView,"red":redColorView]
let layout = NSLayoutFormatOptions(rawValue: 0)
let horizontalContraint:[NSLayoutConstraint] = NSLayoutConstraint.constraintsWithVisualFormat("|-10-[blue]-10-[red]-10-|", options: layout, metrics: nil, views: viewsDictionary)
let verticalContraint_1:[NSLayoutConstraint] = NSLayoutConstraint.constraintsWithVisualFormat("V:|-10-[blue]-10-|", options: layout, metrics: nil, views: viewsDictionary)
let verticalContraint_2:[NSLayoutConstraint] = NSLayoutConstraint.constraintsWithVisualFormat("V:|-10-[red]-10-|", options: layout, metrics: nil, views: viewsDictionary)
self.addConstraints(verticalContraint_1)
self.addConstraints(verticalContraint_2)
self.addConstraints(horizontalContraint)
}
}
The problem is that your horizontal constraints are ambiguous. They are insufficient to resolve to exactly one layout. So, the system has to pick arbitrarily from among the possibilities.
In particular, |-10-[blue]-10-[red]-10-| doesn't specify how wide blue and red should be. Assuming the superview is wider than 30 points, any number of solutions are possible. blue could be 0 width and red could be the superview's width minus 30. Or vice versa. Or anything in between. The only effective constraint on the two subviews' widths is that they add up to the superview's width minus 30. Since you say that only one is visible, presumably the other has been assigned 0 width.
As you've noticed, you can explicitly constrain the width one of the subview or you can specify that they have equal width to each other (or some other ratio).
If the views had intrinsic size, or if they had subviews with intrinsic size and their widths were constrained based on their subviews, then things like content-hugging and compression-resistance priorities would come into play. But plain UIViews like you're using have no intrinsic size, so they don't.

iOS UITableView tableHeaderView resizes after transition/reappear

I'm getting some odd behavior. I'm setting a tableHeaderView as follows:
class MyTableViewController: UITableViewController {
...
override func viewDidLoad() {
...
var myHeaderView = NSBundle.mainBundle().loadNibNamed("MyHeaderView", owner: self, options: nil).first as? MyHeaderView
tableView.tableHeaderView = myHeaderView
...
}
...
}
When the view loads up the first time, it displays correctly. Auto-layout gives it a height of 30, and the table header height adheres to it.
When I segue to another view (via tapping a cell in the UITableView), then hit the back button, the UITableView draws with the correct height as well.
However, a split second after everything loads correctly the tableViewHeader resizes itself and covers a bit of the first cell. This is extremely frustrating because I can't seem to figure out where it's happening.
I added some log lines. Here's what it looks like after hitting the back button:
viewWillAppear: header frame is Optional((0.0, 0.0, 375.0, 30.0))
viewDidLayoutSubviews: header frame is Optional((0.0, 0.0, 375.0, 30.0))
viewDidAppear: header frame is Optional((0.0, 0.0, 375.0, 30.0))
viewDidLayoutSubviews: header frame is Optional((0.0, 0.0, 375.0, 49.0))
viewDidLayoutSubviews: header frame is Optional((0.0, 0.0, 375.0, 49.0))
From what I can tell, something out of my control changes the height of the tableViewHeader between viewDidAppear and viewDidLayoutSubviews. I can't correct the size in viewDidLayoutSubviews because it triggers an infinite loop.
I'm at a loss as to what to do to fix this. Everything seems/behaves fine until the view reappears. It also breaks the correct height on transition to/from landscape.
Found a workaround that seems to resolve this issue. (Inspired by this post.) The problem seems to be that the combination of auto-resizing masks and autolayout causes some confusion in how the UITableView tries to determine header size. So, a good option is to use autolayout to connect the header view to the parent table view.
First, set TranslatesAutoresizingMaskIntoConstraints to false:
class MyTableViewController: UITableViewController {
...
var _myHeaderView: MyHeaderView!
...
override func viewDidLoad() {
...
_myHeaderView = NSBundle.mainBundle().loadNibNamed("MyHeaderView", owner: self, options: nil).first as! MyHeaderView
myHeaderView.setTranslatesAutoresizingMaskIntoConstraints(false)
tableView.tableHeaderView = myHeaderView
...
}
...
}
Then, override the UITableViewController's updateViewConstraints() method to attach constraints:
override func updateViewConstraints() {
var viewDictionary = ["headerView": _myHeaderView]
_myHeaderView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[headerView(30)]", options: nil, metrics: nil, views: viewDictionary))
tableView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[headerView(==tableView)]", options: nil, metrics: nil, views: ["headerView": _myHeaderView, "tableView": tableView]))
tableView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[headerView]", options: nil, metrics: nil, views: viewDictionary))
tableView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[headerView]", options: nil, metrics: nil, views: viewDictionary))
super.updateViewConstraints()
}
This will respond well to view resizing, etc.
You can Call tableview.reloadData() to solve the problem.

How to make a UITextView full width and height of containing UIViewController

I have UITextView that I would like to make the same height and width of it's container. It is in a simple UIViewContainer.
I tried doing the following:
override public func viewDidLoad() {
self.edgesForExtendedLayout = .None
resultText.text = result
resultText.frame = view.frame
}
This seems to work for portrait but not landscape.
All I am trying to do is make the UITextView take up all the space of it's container.
If I could find the answer in Objective-C I could easily translate it to Swift. I am just looking for the answer for iOS.
I suggest you to use auto layout
Then click add 4 constraints.
If any warning,
Click Update Frames
Autolayout is your friend - It can be done easily using Interface Builder, or in code:
override public func viewDidLoad() {
super.viewDidLoad()
self.edgesForExtendedLayout = .None
resultText.text = result
// add vertical constraints to pin the view to the superview edge
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0.0-[resultText]-0.0-|", options: nil, metrics: nil, views: ["resultText": resultText]))
// add horizontal constrains to pin the view to the superview edge
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0.0-[resultText]-0.0-|", options: nil, metrics: nil, views: ["resultText": resultText]))
}

Programmatically retrieve the width and height of a UIView using Auto Layout and NSLayoutConstraints?

How do you get the width and height of a UIView who's size and position are set using Auto Layout and Apple's Visual Format Language?
Here's the code (view is just the variable from UIViewController):
// Create and add the view
var stageView = UIView()
stageView.setTranslatesAutoresizingMaskIntoConstraints(false) // Since I'm using Auto Layout I turn this off
view.addSubview(stageView)
// Create and add constraints to the containing view
let viewsDictionary = ["stageView":stageView]
let horizontalConstraints: NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:|-150-[stageView]-150-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
let verticalConstraints: NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:|-100-[stageView]-150-|", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: viewsDictionary)
view.addConstraints(horizontalConstraints)
view.addConstraints(verticalConstraints)
println("stageView.frame=\(stageView.frame)")
and got:
stageView.frame=(0.0,0.0,0.0,0.0)
so I tried:
let fittingSize = stageView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
println("fittingSize=\(fittingSize)")
and got:
fittingSize=(0.0,0.0)
I can't seem to find a way to get the size. I'm able to add subviews to stageView that place just fine using Auto Layout and Visual Format Language, but I can't get width and height for stageView which I need to further position those subviews.
Any ideas?
You have a few options:
You can force the layout engine to size the views immediately by calling setNeedsLayout and then call layoutIfNeeded. This is not recommended because it's inefficient and any manual frames required for layout might not have been set yet. You can read more about this approach on my answer to this question.
You can also wait until the subviews have been updated in the view controller:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
println("stageView.frame = \(stageView.frame)")
}
If you want to know within a UIView subclass (or more often, a UITableViewCell subclass, you can check after layoutSubviews has run:
override func layoutSubviews() {
super.layoutSubviews()
println("self.frame = \(self.frame)")
}
You need to check the frame inside viewDidLayoutSubviews.
This function run after constraint calculation
Its suppose to look something like this
override func viewDidLayoutSubviews()
{
super.viewDidLayoutSubviews()
//Print frame here
}

Resources