Skip to content

Instantly share code, notes, and snippets.

@artemkrachulov
Last active July 21, 2016 10:48
Show Gist options
  • Save artemkrachulov/4bac6ec1bfffae5ceb49a4cd8fb01151 to your computer and use it in GitHub Desktop.
Save artemkrachulov/4bac6ec1bfffae5ceb49a4cd8fb01151 to your computer and use it in GitHub Desktop.
Load object to instance
//
// UIView+loadFromNib.swift
//
// Created by Artem Krachulov
// Copyright (c) 2016 Artem Krachulov. All rights reserved.
// http://www.artemkrachulov.com
//
import UIKit
extension UIView {
/// Load object to instance where current method was initialized
///
/// - Parameters:
/// - name: Xib or Nib file name. Nil value will use class name
/// - bundle: An NSBundle object. Nil value will returns the NSBundle object that corresponds to the directory.
/// - index: Object index from Xib or Nib file.
func loadFromNib(name: String!, bundle: NSBundle!, index: UInt = 0) {
if let view = UIView.loadFromNib(name ?? NSStringFromClass(self.dynamicType).componentsSeparatedByString(".").last!, owner: self, bundle: bundle, index: index) {
view.frame = bounds
view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
addSubview(view)
} else {
print("Error \(self.dynamicType) \(#function) \n")
print("Can't initialize view \n")
}
}
/// Return object from Xib or Nib file.
///
/// - Parameters:
/// - name: Xib or Nib file name.
/// - owner: The object to assign as the nib’s File's Owner object.
/// - bundle: An NSBundle object. Nil value will returns the NSBundle object that corresponds to the directory.
/// - index: Object index from Xib or Nib file.
class func loadFromNib(name: String, owner: AnyObject!, bundle: NSBundle!, index: UInt = 0) -> UIView! {
let objects = (bundle ?? NSBundle.mainBundle()).loadNibNamed(name, owner: owner, options: nil)
let _index = Int(index)
guard _index <= objects.count - 1 else {
print("Error \(self.dynamicType) \(#function) \n")
print("Index \"\(index)\" out of objects array range \n")
return nil
}
return objects[_index] as! UIView
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment