从 XIB 问题动态实例化自定义 UIView(这段代码有什么问题)?

Dynamically instantiating custom UIView's from XIB issue (what's wrong with this code)?

下面的代码有什么问题,好像是死循环了。最初通过 init:frame,到 commonInit,但随后 XIB 加载线触发通过 init:coder 等再次进入

问题的两个方面:

a) 如何实例化可能会避免这个问题(即想使用 XIB 进行布局,但随后在代码中的父视图上动态 creating/position 多个)

b) 设置 self.label.text 是有问题的,因为此时似乎 self.label(链接到 XIB 的 UILabel)尚未设置,因此为零。所以动态地,当我想通过 XIB 创建这个小的自定义 UIView 时,将其添加为子类,然后立即设置标签的值我该怎么做?

导入 UIKit

class DirectionInfoView: UIView {

    @IBOutlet weak var label: UILabel!

    func commonInit() {
        let viewName = "DirectionInfoView"
        let view: DirectionInfoView = NSBundle.mainBundle().loadNibNamed(viewName, owner: self, options: nil).first as! DirectionInfoView  // <== EXC_BAD_ACCESS (code=2...)
        self.addSubview(view)
        view.frame = self.bounds

        self.label.text = "testing 123"
    }

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

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

}

用法:

 let newInfoView = DirectionInfoView(frame: self.mapview.bounds)
 myexitingView.addSubview(newInfoView)

这似乎有效:

import UIKit

class DirectionInfoView: UIView {
    @IBOutlet weak var label: UILabel!

    func commonInit() {
        self.layer.borderWidth = 5
        self.layer.cornerRadius = 25
    }

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

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

}

用法:

let directionInfoView : DirectionInfoView = NSBundle.mainBundle().loadNibNamed("DirectionInfoView", owner: self, options: nil).first as! DirectionInfoView
mapview.addSubview(directionInfoView)
directionInfoView.label.text = "It Worked!"