Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Vertical UISegmentedControl
//
// UISegmentedControl+Vertical.swift
// Make a UISegmentedControl vertical by setting mySegmentedControl.vertical = true
//
// Created by Yonat Sharon on 14/9/14.
// Copyright (c) 2014 Yonat Sharon. All rights reserved.
//
import UIKit
extension UISegmentedControl {
/// Present segments one below the other vertically.
/// Be sure to re-set after inserting segments.
var vertical : Bool {
get {
return fabs(transform.b) > 0.001
}
set {
// rotate view
self.transform = newValue ? CGAffineTransformMakeRotation(CGFloat(M_PI_2)) : CGAffineTransformIdentity
let padding : CGFloat = 8
let maxSize = CGSize(width: CGFloat.max, height: CGFloat.max)
var size : CGSize
var maxHeight : CGFloat = 0
var totalWidth : CGFloat = 0
// reverse rotate segment content
for segment in subviews {
for contentView in segment.subviews {
size = contentView.sizeThatFits(maxSize)
maxHeight = max(maxHeight, newValue ? size.width : size.height)
totalWidth += (newValue ? size.height : size.width) + padding
contentView.transform = newValue ? CGAffineTransformMakeRotation(-CGFloat(M_PI_2)) : CGAffineTransformIdentity
}
}
// adjust size
bounds = CGRect(x: 0, y: 0, width: totalWidth + padding, height: maxHeight + 2*padding)
}
}
func scaleToFit(size: CGSize) { // keeps aspect ratio
var frameSize = bounds.size
if vertical { swap(&frameSize.width, &frameSize.height) }
let scale = min(size.width / frameSize.width, size.height / frameSize.height)
if scale < 1 {
transform = CGAffineTransformScale(transform, scale, scale)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.