在情节提要中重用 uiview xib [英] Reuse a uiview xib in storyboard
本文介绍了在情节提要中重用 uiview xib的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我通常喜欢在界面生成器中创建和设计我的 uiview.有时我需要在 xib 中创建一个视图,该视图可以在情节提要的多个视图控制器中重用.
I typically like to create and design my uiviews in interface builder. Sometimes I need to create a single view in a xib that can be reused in multiple view controllers in a storyboard.
推荐答案
在故事板中重用和渲染 xib.
使用 Swift 2.2 测试Xcode 7.3.1
- File > New > File > Source > Cocoa Touch Class > UIView
- 文件 > 新建 > 文件 > 用户界面 > 视图
- 选择xib
- 选择文件的所有者
- 在身份检查器中将自定义类设置为DesignableXibView".
- 注意:不要在xib上设置视图的自定义类.只有文件所有者!
// DesignableXibView.swift
import UIKit
@IBDesignable
class DesignableXibView: UIView {
var contentView : UIView?
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
func xibSetup() {
contentView = loadViewFromNib()
// use bounds not frame or it'll be offset
contentView!.frame = bounds
// Make the view stretch with containing view
contentView!.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
// Adding custom subview on top of our view (over any custom drawing > see note below)
addSubview(contentView!)
}
func loadViewFromNib() -> UIView! {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: String(self.dynamicType), bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
}
5 ---- 在故事板中测试您的可重用视图
- 打开您的故事板
- 添加视图
- 设置该视图的自定义类
- 等一下……轰!!
这篇关于在情节提要中重用 uiview xib的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文