Last active
July 19, 2017 22:40
-
-
Save Oni-zerone/9f9a00133737e6767f3e12f03e0052a2 to your computer and use it in GitHub Desktop.
ControlBar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// SOTControlBar.swift | |
// ControlBar | |
// | |
// Created by Andrea Altea on 27/06/17. | |
// Copyright © 2017 StudiOUT. All rights reserved. | |
// | |
import UIKit | |
class SOTControlBar: UIView { | |
var components: Array<UIView>? { | |
willSet { | |
guard let oldComponents = self.components else { | |
return | |
} | |
oldComponents.forEach({ (component) in | |
component.removeFromSuperview() | |
}) | |
} | |
didSet { | |
guard let components = self.components else { | |
return | |
} | |
for index in 0 ..< components.count { | |
let component = components[index] | |
component.translatesAutoresizingMaskIntoConstraints = false | |
self.addSubview(component) | |
self.setConstraints(for: component, with: index > 0 ? components[index-1] : nil) | |
} | |
guard let lastComponent = components.last else { | |
return | |
} | |
let rightConstraint = NSLayoutConstraint.constraint(from: lastComponent, to: self, with: .right) | |
self.addConstraint(rightConstraint) | |
} | |
} | |
private func setConstraints(for component: UIView, with previous: UIView?) { | |
let vConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[component]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["component" : component]) | |
self.addConstraints(vConstraints) | |
guard let previous = previous else { | |
let leftConstraint = NSLayoutConstraint.constraint(from: self, to: component, with: .left) | |
self.addConstraint(leftConstraint) | |
return | |
} | |
let widthConstraint = NSLayoutConstraint.constraint(from: component, to: previous, with: .width) | |
self.addConstraint(widthConstraint) | |
let leftConstraint = NSLayoutConstraint(item: component, attribute: .left, relatedBy: .equal, toItem: previous, attribute: .right, multiplier: 1, constant: 0) | |
self.addConstraint(leftConstraint) | |
} | |
} | |
fileprivate extension NSLayoutConstraint { | |
static func constraint(from fromComponent: UIView, to toComponent: UIView, with attribute: NSLayoutAttribute) -> NSLayoutConstraint { | |
return NSLayoutConstraint(item: fromComponent, attribute: attribute, relatedBy: .equal, toItem: toComponent, attribute: attribute, multiplier: 1, constant: 0) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment