将 xib 文件与 UIViewController 和自定义类链接

Ben*_*bab 0 xib uiview swift swift2

为了创建 xib 文件,我添加了一个新的 UIViewController 的可可触摸文件子类,并选中了“也创建 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.
    }
Run Code Online (Sandbox Code Playgroud)

除了我的 IBoutlet 之外别无他物(我至少检查了连接检查器 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
    }
}
Run Code Online (Sandbox Code Playgroud)

我在我的初始 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)
    }
Run Code Online (Sandbox Code Playgroud)

我仍然有这个错误:

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 文件等。

请你帮助我好吗 ?

谢谢。本

Lon*_*ham 6

你处理方式不对。UIView来自另一个 xib 的习惯UIViewController会引起混淆。但我会让你摆脱这个错误。请参阅下面的设置。

在此处输入图片说明

变化FileOwner来自TestControllerViewControllerCard 在此处输入图片说明 删除Outlet参考: 在此处输入图片说明

将主视图更改为Card. 它可以帮助您投射UIViewCard.

在此处输入图片说明

顺便说一句:我建议您创建新的 xib 文件Card.xib并将其连接到Card.swift