Last active
August 19, 2016 10:17
-
-
Save samrayner/56a6c8371a1a0e44f43f2c1a425579e4 to your computer and use it in GitHub Desktop.
Xib-backed UIView subclass. Set the class name and outlets on the view's owner, not on the view itself!
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
// | |
// XibView.swift | |
// | |
// | |
// Created by Sam Rayner on 29/05/2016. | |
// Copyright © 2016 Sam Rayner. All rights reserved. | |
// | |
import UIKit | |
@IBDesignable | |
class XibView: UIView { | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
addXibView() | |
} | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
addXibView() | |
} | |
func addXibView() { | |
guard let view = loadViewFromNib() else { return } | |
backgroundColor = .clearColor() | |
addSubview(view) | |
fillWithView(view) | |
} | |
func loadViewFromNib() -> UIView? { | |
let klass = self.dynamicType | |
return UINib(nibName: "\(klass)", bundle: NSBundle(forClass: klass)).instantiateWithOwner(self, options: nil).first as? UIView | |
} | |
func fillWithView(view: UIView) { | |
view.frame = bounds | |
view.translatesAutoresizingMaskIntoConstraints = false | |
addConstraint(NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)) | |
addConstraint(NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)) | |
addConstraint(NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0)) | |
addConstraint(NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment