Created
November 22, 2018 12:10
-
-
Save ManWithBear/225065eac4e1001aa783c84db6dda64b to your computer and use it in GitHub Desktop.
Smarty way to init xib views inside other xibs
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 | |
/// thanks to Badoo | |
/// https://github.com/badoo/Chatto/blob/master/ChattoAdditions/Source/Input/ReusableXibView.swift | |
@objc open class ReusableXibView: UIView { | |
func loadViewFromNib() -> UIView { | |
let bundle = Bundle(for: type(of: self)) | |
let nib = UINib(nibName: type(of: self).nibName(), bundle: bundle) | |
let view = nib.instantiate(withOwner: nil, options: nil).first as! UIView | |
return view | |
} | |
override open func awakeAfter(using aDecoder: NSCoder) -> Any? { | |
if self.subviews.count > 0 { | |
return self | |
} | |
let bundle = Bundle(for: type(of: self)) | |
if let loadedView = bundle.loadNibNamed(type(of: self).nibName(), owner: nil, options: nil)?.first as? UIView { | |
loadedView.frame = frame | |
loadedView.autoresizingMask = autoresizingMask | |
loadedView.translatesAutoresizingMaskIntoConstraints = translatesAutoresizingMaskIntoConstraints | |
for constraint in constraints { | |
let firstItem = constraint.firstItem === self ? loadedView : constraint.firstItem | |
let secondItem = constraint.secondItem === self ? loadedView : constraint.secondItem | |
loadedView.addConstraint(NSLayoutConstraint(item: firstItem as Any, attribute: constraint.firstAttribute, relatedBy: constraint.relation, toItem: secondItem, attribute: constraint.secondAttribute, multiplier: constraint.multiplier, constant: constraint.constant)) | |
} | |
return loadedView | |
} else { | |
return nil | |
} | |
} | |
class func nibName() -> String { | |
assert(false, "Must be overriden") | |
return "" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment