我試圖從廈門國際銀行雖然從廈門國際銀行加載子視圖的UIScrollView在迅速
加載自定義的UIView customView.swift
進口的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 {
let nibName:String = "customView"
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: nibName, bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView // **Getting error at this line**
return view
}
}
得到錯誤 'EXC_BAD_ACCESS' customView.xib
文件的所有者是CustomView類。
在故事板
我有一個UIViewController(滾動視圖控制器)與自定義類一個UIView:CustomView。 xib @IBDesignable傳播並且一切都很好。
現在問題就開始了。我試圖使用customView多次(就像在的tableView細胞)在ScrollViewController,就像我做viewOne
MyUIViewController.swift
import UIKit
class MyUIViewController: UIViewController,UIScrollViewDelegate {
let scrollView = UIScrollView()
let height = CGFloat(234.0)
override func viewDidLoad() {
super.viewDidLoad()
self.scrollView.frame = CGRectMake(0, 150, self.view.bounds.size.width, height)
self.scrollView.contentSize = CGSizeMake(height*3,self.view.bounds.size.width)
self.scrollView.backgroundColor = UIColor.redColor()
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 customViewDummy: customView = NSBundle.mainBundle().loadNibNamed("customView", owner: self, options: nil)[0] as! customView
if index == 0{
customViewDummy.backgroundColor = UIColor.greenColor()
}
if index == 1{
customViewDummy.backgroundColor = UIColor.redColor()
}
return customViewDummy
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
我試圖加載自定義在ViewController中多次從筆尖UIView。
我稱爲下面的鏈接 - How to use custom nib view in ViewController multiple times
我使用的Xcode 7.3.1
任何建議表示讚賞。先謝謝你。
不能認爲所有的東西都用'正確的[0]! UIView',檢查數組是否有任何內容,如果是,檢查'[0]'是否具有您期望的對象類型。 –