Last active
December 8, 2017 16:48
-
-
Save xxKRASHxx/17502c94cd847e97f1fc4effbfb495ff to your computer and use it in GitHub Desktop.
Generic protocol for loading views from xib
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
import UIKit | |
class AnyViewClass: UIView {} | |
extension AnyView: NibInstantiable { } | |
let view: AnyViewClass = .fromNib() | |
type(of: view) //will be AnyViewClass |
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
import Foundation | |
import UIKit | |
public protocol NibInstantiatable: class {} | |
public extension UIView { | |
public static func fromNib<AnyView>() -> AnyView | |
where AnyView: NibInstantiatable { | |
guard let view = self.nib | |
.instantiate(withOwner: nil, options: nil) | |
.first as? AnyView else { fatalError("Can not load \(AnyView.self) from xib") } | |
return view | |
} | |
public static var nib: UINib { | |
return UINib( | |
nibName: identifier, | |
bundle: Bundle(for: self) | |
) | |
} | |
public static var identifier: String { | |
return String(describing: self) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment