Skip to content

Instantly share code, notes, and snippets.

@MrAlek
Last active January 14, 2016 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MrAlek/489b9df9a7a4e5309cc1 to your computer and use it in GitHub Desktop.
Save MrAlek/489b9df9a7a4e5309cc1 to your computer and use it in GitHub Desktop.
@IBDesignable view that wraps & renders views from nib files
//
// NibWrapperView.swift
//
// Created by Alek Åström on 2016-01-13.
// http://github.com/mralek
//
// Copyright © 2016 Alek Åström
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
@IBDesignable public class NibWrapperView: UIView {
@IBInspectable public var nibName: String? = nil {
didSet {
guard nibName != oldValue else {
return
}
wrappedView = nibName.flatMap {
return viewFromNib($0)
}
}
}
public private(set) var wrappedView: UIView? {
didSet {
oldValue?.removeFromSuperview()
if let view = wrappedView {
insertSubview(view, atIndex: 0)
view.translatesAutoresizingMaskIntoConstraints = false
addConstraint(topAnchor.constraintEqualToAnchor(view.topAnchor))
addConstraint(leftAnchor.constraintEqualToAnchor(view.leftAnchor))
addConstraint(rightAnchor.constraintEqualToAnchor(view.rightAnchor))
addConstraint(bottomAnchor.constraintEqualToAnchor(view.bottomAnchor))
}
}
}
public override func intrinsicContentSize() -> CGSize {
if let wrappedView = wrappedView {
return wrappedView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
} else {
return CGSize(width: UIViewNoIntrinsicMetric, height: UIViewNoIntrinsicMetric)
}
}
private func viewFromNib(name: String) -> UIView? {
let bundle = NSBundle(forClass: self.dynamicType)
return bundle.loadNibNamed(name, owner: self, options: nil).first as! UIView?
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment