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

时间:2016-05-28 12:31:16

标签: ios uiview xib addsubview loadnibnamed

以下代码有什么问题,它似乎有无穷无尽的循环。最初通过init:frame到commonInit,然后XIB加载行通过init:coder等再次触发输入。

有两个问题:

a)如何实例化以避免这个问题(即想要使用XIB进行布局,然后在代码中的父视图上动态创建/定位其中的多个)

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)

1 个答案:

答案 0 :(得分:1)

这似乎有效:

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!"