Skip to content

Instantly share code, notes, and snippets.

@thomasdegry
Created March 19, 2015 01:38
Show Gist options
  • Save thomasdegry/cac8ffb91e2de291e1a8 to your computer and use it in GitHub Desktop.
Save thomasdegry/cac8ffb91e2de291e1a8 to your computer and use it in GitHub Desktop.
Scrollview with fixed content size
//
// ViewController.swift
// scrollView
//
// Created by LOANER on 3/18/15.
// Copyright (c) 2015 Thomas Degry. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
self.populateScrollView()
}
func populateScrollView() {
var lastImage:UIImageView?
var contentWidth = 0
for var i = 0; i < 4; i++ {
var image = UIImage(named: "image\(i)")
var imageView = UIImageView(image: image)
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.scrollView.addSubview(imageView)
let top = NSLayoutConstraint(item: imageView, attribute: .Top, relatedBy: .Equal, toItem: nil, attribute: .Top, multiplier: 1.0, constant: 0)
let height = NSLayoutConstraint(item: imageView, attribute: .Height, relatedBy: .Equal, toItem: self.scrollView, attribute: .Height, multiplier: 1.0, constant: 0)
let width = NSLayoutConstraint(item: imageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1.0, constant: 300)
var left:NSLayoutConstraint?
if lastImage != nil {
left = NSLayoutConstraint(item: imageView, attribute: .Left, relatedBy: .Equal, toItem: lastImage!, attribute: .Right, multiplier: 1.0, constant: 0)
} else {
left = NSLayoutConstraint(item: imageView, attribute: .Left, relatedBy: .Equal, toItem: nil, attribute: .Left, multiplier: 1.0, constant: 0)
}
lastImage = imageView
contentWidth += Int(self.scrollView.frame.width)
self.scrollView.addConstraints([top, height, width, left!])
}
self.scrollView.contentSize = CGSizeMake(1200, 0)
self.scrollView.pagingEnabled = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment