Created
June 29, 2018 12:22
-
-
Save jonathanduty/c12c5797af83c9aa8955b24d1053cda4 to your computer and use it in GitHub Desktop.
UIView+Extensions
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
| import UIKit | |
| extension UIView { | |
| var absoluteFrame: CGRect { | |
| return self.superview!.convert(self.frame, to: nil) | |
| } | |
| func convertFrame(toParentView parentView: UIView) -> CGRect { | |
| return self.superview!.convert(self.frame, to: parentView) | |
| } | |
| class func fromNib<T : UIView>(named: String? = nil) -> T? { | |
| guard let strongName = named else { | |
| return Bundle.main.loadNibNamed(String(describing: T.self), owner: nil, options: nil)![0] as? T | |
| } | |
| return Bundle.main.loadNibNamed(strongName, owner: nil, options: nil)![0] as? T | |
| } | |
| func circleify() { | |
| self.layer.cornerRadius = self.bounds.size.height / 2 | |
| } | |
| /// Adds constraints to this `UIView` instances `superview` object to make sure this always has the same size as the superview. | |
| /// Please note that this has no effect if its `superview` is `nil` – add this `UIView` instance as a subview before calling this. | |
| func bindFrameToSuperviewBounds(leftMargin: Double = 0, rightMargin: Double = 0, topMargin: Double = 0, bottomMargin: Double = 0) { | |
| guard let superview = self.superview else { | |
| print("Error! `superview` was nil – call `addSubview(view: UIView)` before calling `bindFrameToSuperviewBounds()` to fix this.") | |
| return | |
| } | |
| self.translatesAutoresizingMaskIntoConstraints = false | |
| superview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-\(leftMargin)-[subview]-\(rightMargin)-|", options: .directionLeadingToTrailing, metrics: nil , views: ["subview": self])) | |
| superview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-\(topMargin)-[subview]-\(bottomMargin)-|", options: .directionLeadingToTrailing, metrics: nil, views: ["subview": self])) | |
| } | |
| func toImage() -> UIImage? { | |
| UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0.0) | |
| defer { UIGraphicsEndImageContext() } | |
| if let context = UIGraphicsGetCurrentContext() { | |
| self.layer.render(in: context) | |
| let image = UIGraphicsGetImageFromCurrentImageContext() | |
| return image | |
| } | |
| return nil | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment