簡體   English   中英

在iOS中快速使用容器視圖

[英]Using container view in ios with swift

我只想重用下圖中的ProgressView和3 UILable 我將在許多視圖中重用它們。 這就是為什么我試圖將其創建為Container

在此處輸入圖片說明

我將它們組合為一個容器,然后嘗試以下代碼。

class ViewController: UIViewController {

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    internal var progressViewController : ProgressViewController ;

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }    
}

並且ProgressViewController

class ProgressViewController: UIViewController
{

    @IBOutlet weak var progressView: UIProgressView!
    @IBOutlet weak var lblVLow: UILabel!
    @IBOutlet weak var lblMedium: UILabel!
    @IBOutlet weak var lblVHigh: UILabel!

    override func viewDidLoad() {

    }
}

在嘗試運行此代碼時,出現以下錯誤,

fatal error: init(coder:) has not been implemented,

我不知道這是否正確。 但我希望該盒子可重復使用。 任何想法或幫助將是高度贊賞的。

如果需要將參數傳遞給ProgressViewController,則應通過prepareForSegue 就像是:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "ProgressViewEmbed" {
         let dest = segue.destinationViewController as ProgressViewController;
         dest.strVLow = "Hello"
    }

}

因此,刪除internal var progressViewController並刪除所有init函數。 然后通過非IB變量傳遞參數,然后將這些值分配給ProgressViewController.viewDidLoad() IB值。 類似於以下內容:

class ProgressViewController {
    // IB Outlets
    var strVLow : String!;

    override func viewDidLoad() {
        super.viewDidLoad();
        if let str = strVLow {
            self.lblVLow.text = str;
        }
    }
}

為了更改Embed Segue標識符,請轉到情節提要,然后單擊embed segue並將標識符更改為您需要執行的任何操作: 在此處輸入圖片說明

編輯:完全重建了答案。

UIViewController采用NSCoding協議,該協議需要使用initWithCoder:方法或在Swift中使用init(coder :)。 為了滿足這些需求,您需要注釋出fatalError或將其刪除。 然后需要設置屬性progressViewController,並且您需要調用super.init()。

class ViewController: UIViewController {

    internal var progressViewController : ProgressViewController        

    required init(coder aDecoder: NSCoder) {
        //fatalError("init(coder:) has not been implemented")
        progressViewController = ProgressViewController()
        super.init(coder: aDecoder)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }    
}

暫無
暫無

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

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