【问题标题】:Dynamically instantiating custom UIView's from XIB issue (what's wrong with this code)?从 XIB 问题动态实例化自定义 UIView(此代码有什么问题)?
【发布时间】:2016-05-28 12:31:15
【问题描述】:

以下代码有什么问题,它似乎有一个无限循环。最初是通过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)

【问题讨论】:

    标签: ios uiview xib addsubview loadnibnamed


    【解决方案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!"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-03
      • 1970-01-01
      • 1970-01-01
      • 2017-04-08
      • 2018-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多