簡體   English   中英

Swift 3-從另一個類的XIB實例訪問變量

[英]Swift 3 - Access Variable From Instance Of XIB In Another Class

我已經嘗試了好幾天了,運氣還不太好:(

我想做的是在XIB(稱為BottomNav)實例中設置變量,該實例已存在於另一個名為“ curX”的ViewController中。 我最接近以下幾點:

class Util: NSObject {
    class func loadNib() {
        let nib: BottomNav = Bundle.main.loadNibNamed("BottomNav", owner: self, options: nil)!.first as! BottomNav
        nib.curX = 10
    }
}

這是BottomNav類:

class BottomNav: UIView {
    @IBOutlet var view: UIView!
    @IBOutlet weak var homeBtn: UIView!
    @IBOutlet weak var scroller: UIScrollView!
    @IBOutlet weak var scrollerContent: UIView!

    var curX = 32

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!

        Bundle.main.loadNibNamed("BottomNav", owner: self, options: nil)
        self.addSubview(self.view)
    }

}

這將通過編譯器而沒有任何警告,但是運行時,我收到“此類不符合鍵的鍵值編碼”錯誤。 通常在沒有出口的情況下會出現這種情況,但絕對不是這種情況,我已經使用應用程序中已有的多個XIB對其進行了測試,並且首先通過情節提要加載時沒有問題。 我僅通過“ loadNibNamed”得到此錯誤。

我什至在正確的道路上嗎? 我的想法也許是我的Util類沒有訪問Bundle之類的東西?

class BottomNav: UIView {
    @IBOutlet var view: UIView!
    @IBOutlet weak var homeBtn: UIView!
    @IBOutlet weak var scroller: UIScrollView!
    @IBOutlet weak var scrollerContent: UIView!

    var curX = 32

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

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

    func commonInit(){

        Bundle.main.loadNibNamed("BottomNav", owner: self, options: nil)
        guard let content = view else { return }
        content.frame = self.bounds
        content.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        self.addSubview(content)
    }

}

並且在調用實例時,請嘗試以下操作。

        let instance = BottomNav()
        instance.curX = 30

斯威夫特3.0

我認為您可以從中得到解決方案。 祝一切順利

    var view: UIView!

    override init(frame: CGRect) {

        // call super.init(frame:)
        super.init(frame: frame)

        // 3. Setup view from .xib file
        xibSetup()
    }

    required init?(coder aDecoder: NSCoder) {

        // call super.init(coder:)
        super.init(coder: aDecoder)

        // 3. Setup view from .xib file
        xibSetup()
    }

    // MARK: - UI setup
    func xibSetup() {

        let nib = UINib(nibName: "BottomNav", bundle: nil)
        view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView

        // use bounds not frame or it'll be offset
        view.frame = bounds

        // Make the view stretch with containing view
        view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]

        addSubview(view)
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM