Created
August 20, 2020 07:25
-
-
Save harshvishu/274dfd834554532ea837c3253a47d960 to your computer and use it in GitHub Desktop.
PercentLayoutConstraint
This file contains hidden or 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
// 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