Created
June 14, 2020 08:21
-
-
Save mnaruse/7042776446d51fc6ac2e7ca2c725ec62 to your computer and use it in GitHub Desktop.
Creating a custom UIView from a XIB with IBDesinable.
This file contains hidden or 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-IBDesignable.swift | |
// | |
// Created by MiharuNaruse on 2020/06/14. | |
// Copyright © 2020 m_rn. All rights reserved. | |
// | |
/** | |
https://medium.com/zenchef-tech-and-product/how-to-visualize-reusable-xibs-in-storyboards-using-ibdesignable-c0488c7f525d | |
If you use `Bundle.main.loadNibNamed("XibView", owner: self, options: nil)` , an error will occur like below... | |
~~~ | |
error: IB Designables: Failed to render and update auto layout status for UseXibViewFirstViewController (ZaM-GP-gg5): The agent threw an exception. | |
~~~ | |
The main bundle represents the bundle directory that contains the currently executing code. | |
If your app interacts directly with plug-ins, frameworks, or other bundled content, you can use other methods of this class to create appropriate bundle objects. | |
~~~ | |
// Get the app's main bundle | |
let mainBundle = Bundle.main | |
// Get the bundle containing the specified private class. | |
let myBundle = Bundle(for: NSClassFromString("MyPrivateClass")!) | |
~~~ | |
*/ | |
import UIKit | |
@IBDesignable | |
final class XibView: UIView { | |
var contentView: UIView! | |
// コードから初期化 | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
commonInit() | |
} | |
// IBから初期化 | |
required init?(coder: NSCoder) { | |
super.init(coder: coder) | |
commonInit() | |
} | |
func commonInit() { | |
contentView = loadViewFromNib() | |
addSubview(contentView) | |
contentView.frame = bounds | |
contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight] | |
} | |
/// nibファイルからビューをロードする。 | |
/// | |
/// `Bundle.main.loadNibNamed("ContactView", owner: self, options: nil)` だと、 `@IBDesignable` が機能しない。 | |
/// - Returns: nibファイルから読み込んだビュー | |
func loadViewFromNib() -> UIView? { | |
let bundle = Bundle(for: type(of: self)) | |
let nib = UINib(nibName: "XibView", bundle: bundle) | |
return nib.instantiate(withOwner: self, options: nil).first as? UIView | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment