Skip to content

Instantly share code, notes, and snippets.

@harshvishu
Created August 20, 2020 07:25
Show Gist options
  • Save harshvishu/274dfd834554532ea837c3253a47d960 to your computer and use it in GitHub Desktop.
Save harshvishu/274dfd834554532ea837c3253a47d960 to your computer and use it in GitHub Desktop.
PercentLayoutConstraint
// PercentLayoutConstraint.swift
import Foundation
import UIKit
@IBDesignable
final class PercentLayoutConstraint: NSLayoutConstraint {
@IBInspectable var marginPercent: CGFloat = 0
var screenSize: (width: CGFloat, height: CGFloat) {
return (UIScreen.main.bounds.width, UIScreen.main.bounds.height)
}
override func awakeFromNib() {
super.awakeFromNib()
guard marginPercent > 0 else { return }
NotificationCenter.default.addObserver(self, selector: #selector(layoutDidChange), name: UIDevice.orientationDidChangeNotification, object: nil)
layoutDidChange()
}
/**
Re-calculate constant based on orientation and percentage.
*/
@objc func layoutDidChange() {
guard marginPercent > 0 else { return }
switch firstAttribute {
case .top, .topMargin, .bottom, .bottomMargin:
constant = screenSize.height * marginPercent
case .leading, .leadingMargin, .trailing, .trailingMargin:
constant = screenSize.width * marginPercent
default: break
}
}
deinit {
guard marginPercent > 0 else { return }
NotificationCenter.default.removeObserver(self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment