0

次のコードの問題点は、無限ループになっているようです。最初は init:frame を介して commonInit に到達しますが、その後、XIB ロード行が init:coder などを介して再び開始されます。

問題の 2 つの領域:

a)おそらくこの問題を回避するためにインスタンス化する方法(つまり、XIBを使用してレイアウトしたいが、コードで親ビューにこれらの複数を動的に作成/配置したい)

b)self.label(XIBにリンクされたUILabel)がこの時点で設定されていないため、self.label.textの設定には問題があります。動的に、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)
4

1 に答える 1

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!"
于 2016-05-28T23:34:14.827 に答える