2017-02-07 28 views
0

好傢伙我試圖做一些util的,我需要一個像圖鑑KKiOS的 - 如何當我使用的UIView來的UIViewController

但我有一些問題,設置選擇器的數據。我在不同的視圖中選擇選擇器,然後在tabview中調用該視圖並使用它。

但我不知道如何設置數據。如果我在uiviewcontroller中進行選擇,我可以在設置數據didload?方法,但在uiview中沒有didload我可以設置的方法。

這是我的代碼

SelectPoke.swift

class SelectPoke: UIView , UIPickerViewDelegate , UIPickerViewDataSource{ 
@IBOutlet var textField: UITextField! 

var data = ["1","2","3"] 
var picker = UIPickerView() 

public func numberOfComponents(in pickerView: UIPickerView) -> Int { 
    return 1 
} 

public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{ 
    return data.count 
} 

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { 
    textField.text = data[row] 
} 

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { 
    return data[row] 
} 

func h(){ 
    picker.delegate = self 
    picker.dataSource = self 
} 

override func awakeFromNib() { 
    h() 
} 

class func instanceFromNib() -> UIView { 
    return UINib(nibName: "SelectPoke", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView 
} 

}

Tab1ViewController.swift

class Tab1ViewController: UIViewController { 

override func viewDidLoad() { 
    super.viewDidLoad() 


    let sideView = SelectPoke.instanceFromNib() 
    sideView.frame = self.view.frame 

    self.view.addSubview(sideView) 
} 

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

}

plz幫助我。我的寵物小精靈等待..

+0

是否真的打算將SelectPoke用作UIView子類? 通常你會在'Tab1ViewController'中實現委託和數據源。 –

+0

檢查加載視圖時是否調用initWithCoder方法。 –

回答

0

通常情況下,你會不會繼承UIPickerView,但創建一個故事板(或XIB文件)的景色, 連接與Tab1ViewController委託和數據源。

然而,在這段代碼中我們只在viewDidLoad創建一個新的UIPickerView,保持代碼類似於原來的問題

:目前我沒有任何的Xcode的運行,所以有可能是小syntactial此代碼示例中的錯誤

class Tab1ViewController: UIViewController, UIPickerViewDelegate , UIPickerViewDataSource { 

    var data = ["1","2","3"] 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     let sideView = UIPickerView() 
     sideView.frame = self.view.frame 

     self.view.addSubview(sideView) 
     sideView.delegate = self 
     sideView.dataSource = self 

    } 

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

    public func numberOfComponents(in pickerView: UIPickerView) -> Int { 
     return 1 
    } 

    public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{ 
     return data.count 
    } 

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { 
     textField.text = data[row] 
    } 

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { 
     return data[row] 
    } 
} 
相關問題