Created
June 20, 2016 13:42
-
-
Save drosenstark/13643582c07b0beff2b44d2993c0db75 to your computer and use it in GitHub Desktop.
Allows you to put a UIView inside a Nib that gets loaded from another Nib
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
// | |
// HasOwnNib.swift | |
// PlayingWithUI | |
// | |
// Created by dr2050 on 6/19/16. | |
// Copyright © 2016 Confusion Studios LLC. All rights reserved. | |
// | |
import UIKit | |
// NOTES: | |
// 1) Nib's owner is UIView conforming to HasOwnNib | |
// 2) Nib's first object after owner is a UIView (1st Subview) | |
// 3) 1st Subview will be automatically added to Nib's owner as subview | |
// 4) If you overwrite awakeFromNib, make sure to call super! Protocol is the super | |
protocol HasOwnNib { | |
func nibName() -> String | |
func bundle() -> NSBundle | |
} | |
extension UIView { | |
// this works if the type is specified with @objc(ViewName) | |
func nibName() -> String { | |
return String(self.dynamicType) | |
} | |
func bundle() -> NSBundle { | |
return NSBundle.mainBundle() | |
} | |
public override func awakeFromNib() { | |
if self is HasOwnNib { | |
loadSelfFromNib() | |
} | |
super.awakeFromNib() | |
} | |
// Call from awakeFromNib | |
// Class must be declared with @objc tag with same name as Nib | |
func loadSelfFromNib() { | |
let name = nibName() | |
let bundleObjects = bundle().loadNibNamed(name, owner: self, options: nil) | |
let firstView = bundleObjects[0] as! UIView | |
firstView.backgroundColor = UIColor.clearColor() | |
firstView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] | |
firstView.frame = self.bounds | |
self.addSubview(firstView) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment