Skip to content

Instantly share code, notes, and snippets.

@garmstro
Created May 18, 2015 18:17
Show Gist options
  • Save garmstro/b6341f589e461080dd1a to your computer and use it in GitHub Desktop.
Save garmstro/b6341f589e461080dd1a to your computer and use it in GitHub Desktop.
Programmatically add a vertical slider to a ViewController and adjust for orientation changes
//
// ViewController.swift
//
// Created by Geoff Armstrong on 3/31/15.
// Copyright (c) 2015 Geoff Armstrong. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var slider: UISlider!
//MARK: - Override functions
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Initialize slider as 0, then update once we have the frame properties.
slider = UISlider(frame: CGRectZero)
//Rotate to a vertical slider
slider.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI_2))
slider.value = 0.5
slider.addTarget(self, action: "sliderChanged:", forControlEvents: .ValueChanged)
slider.continuous = false
slider.hidden = true
}
override func viewWillAppear(animated: Bool) {
//Now that we have a frame, set the slider frame
let xPos = view.frame.maxX - view.frame.width * 0.1
let yPos = view.frame.minY + view.frame.height * 0.1
let width = view.frame.width * 0.1
let height = view.frame.height * 0.8
let sliderFrame = CGRect(x: xPos, y: yPos, width: width, height: height)
slider.frame = sliderFrame
slider.hidden = false
}
//This is called after the rotation, thus it has the correct size
override func viewWillLayoutSubviews() {
//Update the slider
let xPos = view.frame.maxX - view.frame.width * 0.1
let yPos = view.frame.minY + view.frame.height * 0.1
let width = view.frame.width * 0.1
let height = view.frame.height * 0.8
let sliderFrame = CGRect(x: xPos, y: yPos, width: width, height: height)
slider.frame = sliderFrame
}
func sliderChanged(sender: UISlider) {
//Use the value from the slider for something
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment