我有一个称为MyClass
的子类UIView
,我想用一个XIB
文件初始化。我不确定如何使用名为xib的文件初始化此类View.xib
class MyClass: UIView {
// what should I do here?
//init(coder aDecoder: NSCoder) {} ??
}
我有一个称为MyClass
的子类UIView
,我想用一个XIB
文件初始化。我不确定如何使用名为xib的文件初始化此类View.xib
class MyClass: UIView {
// what should I do here?
//init(coder aDecoder: NSCoder) {} ??
}
Answers:
我测试了这段代码,它很好用:
class MyClass: UIView {
class func instanceFromNib() -> UIView {
return UINib(nibName: "nib file name", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as UIView
}
}
初始化视图并按如下方式使用它:
var view = MyClass.instanceFromNib()
self.view.addSubview(view)
要么
var view = MyClass.instanceFromNib
self.view.addSubview(view())
更新Swift> = 3.x和Swift> = 4.x
class func instanceFromNib() -> UIView {
return UINib(nibName: "nib file name", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
}
var view = MyClass.instanceFromNib()
&self.view.addSubview(view)
而不是var view = MyClass.instanceFromNib
&self.view.addSubview(view())
。只是改善建议的一个小建议:)
尽管Sam的解决方案没有考虑不同的捆绑软件(NSBundle:forClass可以解决),但它的解决方案已经非常出色,并且需要手动加载,也就是键入代码。
如果要全面支持Xib Outlet,不同的Bundle(在框架中使用!),并在Storyboard中获得不错的预览,请尝试以下操作:
// NibLoadingView.swift
import UIKit
/* Usage:
- Subclass your UIView from NibLoadView to automatically load an Xib with the same name as your class
- Set the class name to File's Owner in the Xib file
*/
@IBDesignable
class NibLoadingView: UIView {
@IBOutlet weak var view: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
nibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
nibSetup()
}
private func nibSetup() {
backgroundColor = .clearColor()
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
view.translatesAutoresizingMaskIntoConstraints = true
addSubview(view)
}
private func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: String(self.dynamicType), bundle: bundle)
let nibView = nib.instantiateWithOwner(self, options: nil).first as! UIView
return nibView
}
}
照常使用您的xib,即将Outlets连接到File Owner,并将File Owner类设置为您自己的类。
用法:从NibLoadingView和类名设置只要继承自己的视图类文件的所有者在XIB文件
不再需要其他代码。
贷项到期的贷项:与GH上的DenHeadless进行了细微的更改,从而进行了分叉。我的要旨:https : //gist.github.com/winkelsdorf/16c481f274134718946328b6e2c9a4d8
nibSetup
from init?(coder:)
会导致无限递归NibLoadingView
。
.clearColor()
从情节提要加载后,nibSetup()将背景颜色覆盖为-的缘故。但是,如果在实例化之后通过代码执行此操作,则它应该可以工作。无论如何,如前所述,一种更为优雅的方法是基于协议的方法。因此,可以肯定的是,这里有您的链接:github.com/AliSoftware/Reusable。现在,我针对UITableViewCells使用了类似的方法(在发现真正有用的项目之前就已实现了该方法)。hth!
从Swift 2.0开始,您可以添加协议扩展。我认为这是一种更好的方法,因为返回类型Self
不是UIView
,所以调用者不需要转换为视图类。
import UIKit
protocol UIViewLoading {}
extension UIView : UIViewLoading {}
extension UIViewLoading where Self : UIView {
// note that this method returns an instance of type `Self`, rather than UIView
static func loadFromNib() -> Self {
let nibName = "\(self)".characters.split{$0 == "."}.map(String.init).last!
let nib = UINib(nibName: nibName, bundle: nil)
return nib.instantiateWithOwner(self, options: nil).first as! Self
}
}
var myView = nib.instantiate... as! myViewType
Swift 3
(XCode 8.0 beta 6)在项目中打开并测试的代码,没有出现问题。错字了Swift 2
。当此答案很好并且用户使用XC8时,用户可能希望搜索哪些变化时,为什么还要选择另一个答案
这就是Frederik在Swift 3.0上的答案
/*
Usage:
- make your CustomeView class and inherit from this one
- in your Xib file make the file owner is your CustomeView class
- *Important* the root view in your Xib file must be of type UIView
- link all outlets to the file owner
*/
@IBDesignable
class NibLoadingView: UIView {
@IBOutlet weak var view: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
nibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
nibSetup()
}
private func nibSetup() {
backgroundColor = .clear
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.translatesAutoresizingMaskIntoConstraints = true
addSubview(view)
}
private func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let nibView = nib.instantiate(withOwner: self, options: nil).first as! UIView
return nibView
}
}
从xib加载视图的通用方法:
例:
let myView = Bundle.loadView(fromNib: "MyView", withType: MyView.self)
实现方式:
extension Bundle {
static func loadView<T>(fromNib name: String, withType type: T.Type) -> T {
if let view = Bundle.main.loadNibNamed(name, owner: nil, options: nil)?.first as? T {
return view
}
fatalError("Could not load view with type " + String(describing: type))
}
}
Swift 3回答:就我而言,我想在我的自定义类中有一个可以修改的插座:
class MyClassView: UIView {
@IBOutlet weak var myLabel: UILabel!
class func createMyClassView() -> MyClass {
let myClassNib = UINib(nibName: "MyClass", bundle: nil)
return myClassNib.instantiate(withOwner: nil, options: nil)[0] as! MyClassView
}
}
在.xib中时,请确保“自定义类”字段为MyClassView。不要打扰文件的所有者。
实例化它:
let myClassView = MyClassView.createMyClassView()
myClassView.myLabel.text = "Hello World!"
斯威夫特4
在这种情况下,我必须将数据传递到该自定义视图中,因此我创建了静态函数来实例化该视图。
创建UIView扩展
extension UIView {
class func initFromNib<T: UIView>() -> T {
return Bundle.main.loadNibNamed(String(describing: self), owner: nil, options: nil)?[0] as! T
}
}
创建MyCustomView
class MyCustomView: UIView {
@IBOutlet weak var messageLabel: UILabel!
static func instantiate(message: String) -> MyCustomView {
let view: MyCustomView = initFromNib()
view.messageLabel.text = message
return view
}
}
实例化视图
let view = MyCustomView.instantiate(message: "Hello World.")
override func draw(_ rect: CGRect)
{
AlertView.layer.cornerRadius = 4
AlertView.clipsToBounds = true
btnOk.layer.cornerRadius = 4
btnOk.clipsToBounds = true
}
class func instanceFromNib() -> LAAlertView {
return UINib(nibName: "LAAlertView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! LAAlertView
}
@IBAction func okBtnDidClicked(_ sender: Any) {
removeAlertViewFromWindow()
UIView.animate(withDuration: 0.4, delay: 0.0, options: .allowAnimatedContent, animations: {() -> Void in
self.AlertView.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
}, completion: {(finished: Bool) -> Void in
self.AlertView.transform = CGAffineTransform.identity
self.AlertView.transform = CGAffineTransform(scaleX: 0.0, y: 0.0)
self.AlertView.isHidden = true
self.AlertView.alpha = 0.0
self.alpha = 0.5
})
}
func removeAlertViewFromWindow()
{
for subview in (appDel.window?.subviews)! {
if subview.tag == 500500{
subview.removeFromSuperview()
}
}
}
public func openAlertView(title:String , string : String ){
lblTital.text = title
txtView.text = string
self.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
appDel.window!.addSubview(self)
AlertView.alpha = 1.0
AlertView.isHidden = false
UIView.animate(withDuration: 0.2, animations: {() -> Void in
self.alpha = 1.0
})
AlertView.transform = CGAffineTransform(scaleX: 0.0, y: 0.0)
UIView.animate(withDuration: 0.3, delay: 0.2, options: .allowAnimatedContent, animations: {() -> Void in
self.AlertView.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
}, completion: {(finished: Bool) -> Void in
UIView.animate(withDuration: 0.2, animations: {() -> Void in
self.AlertView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
})
})
}