使用UIViewController和Custom Class链接xib文件

时间:2015-07-27 17:34:29

标签: swift uiview xib swift2

为了创建xib文件,我添加了一个新的UIViewController的cocoa touch文件子类,并检查了"还创建了XIB文件"。

我的xib文件中只有一个标签。

在我的视图控制器中:

import UIKit

class TestControllerViewController: UIViewController {

    @IBOutlet weak var label: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

除了我的IBoutlet之外别无其他(我至少检查了连接Inspector 10次)。

我的自定义课程:

import Foundation
import UIKit


class Card: UIView {
    internal var number:Int?

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

    }

    convenience init()
    {
        self.init()
    }

}

extension UIView {
    class func loadFromNibNamed(nibNamed: String, bundle : NSBundle? = nil) -> UIView? {
        return UINib(
            nibName: nibNamed,
            bundle: bundle
            ).instantiateWithOwner(nil, options: nil)[0] as? UIView
    }
}

我在初始viewController中实例化这个xib文件:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        var test:Card = Card.loadFromNibNamed("TestControllerViewController")! as! Card
        test.number = 18
        //self.view.addSubview(test)
    }

我仍然有这个错误:

2015-07-27 17:48:52.919 TestXib[6865:578635] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSObject 0x7fcec14b1970> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key label.'

我不知道为什么,我试图清理/重建,删除DerivedData,再次创建xib文件等。

你能帮帮我吗?

感谢&#39;第 本

1 个答案:

答案 0 :(得分:3)

你处理错误的方式。来自另一个UIView的xib的自定义UIViewController会混淆。但我会带你走出这个bug。见下面的设置。

enter image description here

FileOwnerTestControllerViewController更改为Card enter image description here 删除Outlet引用: enter image description here

将主视图更改为Card。它帮助您将UIView投射到Card

enter image description here

BTW:我建议您创建新的xib文件Card.xib并将其与Card.swift

连接