我正在尝试从 nib 加载自定义 UIView
CustomView.swift
import UIKit
@IBDesignable class CustomView: UIView {
var view: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
func xibSetup() {
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
addSubview(view)
}
func loadViewFromNib() -> UIView {
var nibName:String = "CustomView"
var bundle = NSBundle(forClass: self.dynamicType)
var nib = UINib(nibName: nibName, bundle: bundle)
var view = nib.instantiateWithOwner(self, options: nil)[0] as UIView
return view
}
}
CustomView.xib
文件的所有者是 CustomView 类。
In StoryBoard
我有一个 UIViewController( ScrollView Controller )和一个带有自定义类的 UIView:CustomView。 xib @IBDesignable 传播通过,一切正常。
现在问题开始了。我试图在 ScrollViewController 中多次使用 customView(就像 tableView 中的单元格一样),就像我对 viewOne 所做的一样
ScrollViewController.swift
import UIKit
class ScrollViewController: UIViewController {
let scrollView = UIScrollView()
override func viewDidLoad() {
super.viewDidLoad()
let height = CGFloat(200.0)
self.scrollView.frame = self.view.bounds
self.scrollView.contentSize = CGSizeMake(self.view.bounds.size.width, height*3)
self.view.addSubview(self.scrollView)
var y = CGFloat(0.0)
for i in 0..<2 {
//Adding viewOne
let viewOne = self.createViewOne(i)
viewOne.frame = CGRectMake(0, y, 320, 200)
self.scrollView.addSubview(viewOne)
//Adding CustomView
let customView = self.createCustomView(i)
customView.frame = CGRectMake(0, y, 320, 200)
self.scrollView.addSubview(customView)
y += height
}
}
func createViewOne(index: Int) -> UIView {
let viewOne = UIView()
if index == 0{
viewOne.backgroundColor = UIColor.greenColor()
}
if index == 1{
viewOne.backgroundColor = UIColor.redColor()
}
return viewOne
}
func createCustomView(index: Int) -> UIView {
let customView: CustomView = NSBundle.mainBundle().loadNibNamed("CustomView", owner: self, options: nil)[0] as CustomView --> Code breaks here
if index == 0{
customView.backgroundColor = UIColor.greenColor()
}
if index == 1{
customView.backgroundColor = UIColor.redColor()
}
return customView
}
}
问题 代码在下面的行中断并且控制台输出没有帮助(lldb)
let customView: CustomView = NSBundle.mainBundle().loadNibNamed("CustomView", owner: self, options: nil)[0] as CustomView
我也试过用这段代码实例化:
customView = CustomView.loadViewFromNib()
但随后出现错误“调用中参数 #1 缺少参数”
1) 如何在 ViewController 中多次从 nib 加载自定义 UIView。 2) 如何更改 View 中包含的 UI 元素,例如 UIImageView、UILabels 等。我怎样才能设置像 customView.title.text = "Fido"这样的标题
任何帮助将不胜感激!谢谢。
请您参考如下方法:
您的 View 类的全部要点在于它加载 Nib 并将创建的 View 添加为 subview 。它也被定义为 Nib 的所有者。
因此,当您的 View Controller 尝试将自己作为所有者加载 nib 时,它调用了所有 outlet setter,但它没有实现它们,因此它中断了。
要修复,您应该分配并初始化 View ,而不是在 View Controller 中显式地从 Nib 加载它。
替换
let customView: CustomView = NSBundle.mainBundle().loadNibNamed("CustomView", owner: self, options: nil)[0] as CustomView
与
let customView = CustomView()
