![](/img/trans.png)
[英]IOS Swift - Passing data between view controllers using container view
[英]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.