我正在尝试从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类。
在StoryBoard中
我有一个带有自定义类的UIView的UIViewController(Scroll View Controller):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()
然后我得到错误&#34;在调用&#34;
中缺少参数#1的参数1)如何在ViewController中多次从nib加载自定义UIView。 2)如何更改视图中包含的UI元素,例如UIImageView,UILabels等。如何设置标题,如customView.title.text =&#34; Fido&#34;
非常感谢任何帮助!谢谢。
答案 0 :(得分:3)
视图类的重点是加载nib并将创建的视图添加为子视图。它也被定义为笔尖的所有者。
因此,当您的视图控制器尝试将自己作为所有者加载nib时,它会调用所有的插座设置器,但它没有实现它们,因此它会中断。
要修复,你应该分配并启动视图,而不是在视图控制器中明确地从nib加载它。
替换
let customView: CustomView = NSBundle.mainBundle().loadNibNamed("CustomView", owner: self, options: nil)[0] as CustomView
与
let customView = CustomView()