【发布时间】:2015-02-16 22:21:16
【问题描述】:
我正在尝试从 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 类。
在故事板中
我有一个 UIViewController(滚动视图控制器)和一个带有自定义类的 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) 如何更改视图中包含的 UI 元素,例如 UIImageView、UILabels 等。如何设置标题,如 customView.title.text = "Fido"
任何帮助将不胜感激!谢谢。
【问题讨论】: