UIScrollView does not fit with constraints - ios

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.

Related

UIView doesn't appear as subview

I have a cell with subviews.
I can't figure out why the UIView boom isn't visible. Here is my code:
let separator: UIView = {
let view = UIView()
view.backgroundColor = .yellow
return view
}()
let boom: UIView = {
let b = UIView()
b.backgroundColor = .red
return b
}()
override func setupViews() {
super.setupViews()
addSubview(separator)
addSubview(setNumberView)
addSubview(boom)
backgroundColor = .orange
addConstraintsWithFormat("H:|-20-[v0]", views: boom)
addConstraintsWithFormat("V:|-20-[v0]", views: boom)
addConstraintsWithFormat("H:|[v0]|", views: separator)
addConstraintsWithFormat("V:[v0(10)]|", views: separator)
separator shows up as it is supposed to. Is there a bug in my xcode or something? I have tried restarting xcode, putting the view into a frame, and changing the cell size.
You are not setting any width or height to your view.
To properly setup the position of a view, you have to specify the horizontal position, the vertical position, the width and height.
The separator correctly specifies all of them, the view is missing constraints for width and height.
A way to fix that could be for example:
addConstraintsWithFormat("H:|-20-[v0]-20-|", views: boom)
addConstraintsWithFormat("V:|-20-[v0(100)]", views: boom)

How do I constrain UIView to UICollectionViewCell

Opposite of what everyone else seems to be asking. I have a collectionView with cells into which I am adding a loaded .xib as a subview. Easy enough.
However, the size of the collectionView cells change at run-time based on different criteria so I need the subview to be properly constrained to the size of the collectionViewCell's contentView. In an attempt to do this, I have this code when I add the subview:
/**
Used to present a view in the collectionView. WidetView is a subclass of UIView
*/
class WidgetCell: UICollectionViewCell, Reusable {
var widgetView: WidgetView! {
didSet {
for view in contentView.subviews {
view.removeFromSuperview()
}
contentView.addSubview(widgetView)
let views = ["view": widgetView as Any]
var constraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: views)
constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: views))
contentView.addConstraints(constraints)
}
}
}
Unfortunately, what's presented isn't a set of views that are properly constrained. The added UIView is the same size as what's defined in the .xib.
How can I fix this? If you want a sample project (Swift 3) look here: https://github.com/AaronBratcher/FitToCell
It's a simple case of calling contentView.activateConstraints(constraints) with your existing code and then at the point where the cells are shown, cell.layoutIfNeeded(). This forces the cell to recalculate the bounds of it's subviews.
Since the expected size of the cell is known for layout purposes, pass that size to the WidgetCell instance and then set the view's frame size.
final class WidgetCell: UICollectionViewCell {
var cellSize: CGSize?
var widgetView: WidgetView! {
didSet {
for view in contentView.subviews {
view.removeFromSuperview()
}
let frame: CGRect
if let cellSize = cellSize {
frame = CGRect(origin: CGPoint(x: 0, y: 0), size: cellSize)
} else {
frame = contentView.frame
}
widgetView.frame = frame
widgetView.setNeedsLayout()
contentView.addSubview(widgetView)
}
}
}

How to set constraints for a reusable UIView in Swift with auto layout?

I'm trying to build a reusable UIView whose width should equal to its superview in Swift.
Since the size of its superview varies, I think I have to set constraints for it with auto layout.
But I can't figure out how to do it programmatically in Swift.
Here is the code for the reusable subview:
import UIKit
class bottomMenu: UIView {
#IBOutlet var bottomMenu: UIView!
required init(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
NSBundle.mainBundle().loadNibNamed("bottomMenu", owner: self, options: nil)
bottomMenu.backgroundColor = UIColor.redColor()
//How to make the width of the bottom Menu equal to its superview?
self.addSubview(self.bottomMenu)
}
}
Can anyone show me how to make it?
Thanks
You can override didMoveToSuperview() method in your UIView subclass and add the constraints there:
override func didMoveToSuperview() {
super.didMoveToSuperview()
backgroundColor = UIColor.redColor()
let views = ["view" : self];
self.setTranslatesAutoresizingMaskIntoConstraints(false)
self.superview?.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[view]|", options: NSLayoutFormatOptions(0), metrics: nil, views: views))
self.superview?.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: NSLayoutFormatOptions(0), metrics: nil, views: views))
}
Add constraints for element inside. For each element add constraint for top, bottom, left and right. If you have any images that needs to be same size add width and height as well. If you can post the screenshot of the UIView I will add more information and will be able to be more helpful.
Also take a look at http://www.raywenderlich.com/50317/beginning-auto-layout-tutorial-in-ios-7-part-1 if you are new to autolayout.
The following code gives the loaded view the same height and width as the super view. (not sure what you wanted for height)
bottomMenu.setTranslatesAutoresizingMaskIntoConstraints(false)
//Views to add constraints to
let views = Dictionary(dictionaryLiteral: ("bottomMenu",bottomMenu))
// Horizontal constraints
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[bottomMenu]|", options: nil, metrics: nil, views: views)
self.addConstraints(horizontalConstraints)
// Vertical constraints
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[bottomMenu]|", options: nil, metrics: nil, views: views)
self.addConstraints(verticalConstraints)

Swift - constraint issues with UIScrollView (programmatically)

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.

A view height is 568 on 3.5-inch screen

I need to create a view with a scroll view and a page control in it, and place 7 views inside scroll view.
To lay out subviews inside the scroll view I use pure Auto layout Approach, that is described here.
So I have my controller with XIB file (I don't use storyboards here) that is pretty simple: it's a UIScrollView and UIPageControl with all constraints set up.
And I have a XIB for a UIView subclass Slide which has 2 UIImageViews and 1 UILabel, and there's also some constraints.
To add some views to UIScrollView I use this code in viewDidLayoutSubviews():
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.setTranslatesAutoresizingMaskIntoConstraints(false)
var pSlide: Slide?
for var i = 0; i < 7; i++ {
var slide = Slide(frame: self.view.bounds, imageName: "slide-\(i+1)-bg", text: NSLocalizedString("slides_\(i+1)", comment: ""))
slide.setTranslatesAutoresizingMaskIntoConstraints(false)
scrollView.addSubview(slide)
var dict: [NSObject : AnyObject] = ["currentSlide" : slide]
if let previousSlide = pSlide {
dict["previousSlide"] = previousSlide
let constraintsHorizontal = NSLayoutConstraint.constraintsWithVisualFormat("H:[previousSlide][currentSlide]", options: nil, metrics: nil, views: dict)
scrollView.addConstraints(constraintsHorizontal)
let constraintsVertical = NSLayoutConstraint.constraintsWithVisualFormat("V:|[currentSlide]|", options: nil, metrics: nil, views: dict)
scrollView.addConstraints(constraintsVertical)
} else {
let constraintsVertical = NSLayoutConstraint.constraintsWithVisualFormat("V:|[currentSlide]|", options: nil, metrics: nil, views: dict)
scrollView.addConstraints(constraintsVertical)
let constraintsLeft = NSLayoutConstraint.constraintsWithVisualFormat("H:|[currentSlide]", options: nil, metrics: nil, views: dict)
scrollView.addConstraints(constraintsLeft)
}
if i == 6 {
let constraintsRight = NSLayoutConstraint.constraintsWithVisualFormat("H:[currentSlide]|", options: nil, metrics: nil, views: dict)
scrollView.addConstraints(constraintsRight)
}
pSlide = slide
}
pageControl.numberOfPages = numberOfSlides
view.layoutSubviews()
}
In this piece of code I create a Slide instance, and set all necessary constraints to it, according to pure Auto Layout approach.
init() method of the Slide class looks like this:
init(frame: CGRect, imageName: String, text: String) {
super.init(frame: frame)
NSBundle.mainBundle().loadNibNamed("Slide", owner: self, options: nil)
self.addSubview(self.view)
self.view.frame = frame
self.layoutIfNeeded()
println("Frame is \(frame); view.frame is \(self.view.frame)")
backgroundImage.image = UIImage(named: imageName)
textLabel.text = text
}
I hoped that
self.view.frame = frame
self.layoutIfNeeded()
will help me but no. The problem is, on 3.5 inch screen all my UIScrollView subviews have the height of 568, which is the normal height for 4 inch display, but not for 3.5 inch.
I'm checking the height in viewDidAppear(animated:) method. But, in init() method of Slide class the height appears to be ok — 480.
I'm trying to solve it for second day already, and still nothing works. I know that this may be much more simple to implement without using Auto Layout and Interface Builder, but I need to do it with these.
I used UIPageViewController instead of all this mess, and it works just fine.

Resources