2014-11-04 55 views
6

我想添加一個pickerview到我的iphone應用程序,而不是從我的數組顯示字符串它顯示問號。有誰知道爲什麼?我一直在試圖弄明白了幾個小時了......這是我的一個包含pickerview控制器代碼:pickerView顯示爲問號而不是數據?

class NewIssueViewController: UIViewController, UIPickerViewDelegate { 

    var componentArr = ["component1","component2","component3","component4"] 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view. 


    } 

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

    @IBAction func CancelPressed(sender: AnyObject) { 
     self.dismissViewControllerAnimated(true, completion: nil) 
    } 

    @IBAction func AddPressed(sender: AnyObject) { 
     self.dismissViewControllerAnimated(true, completion: nil) 
    } 

    func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int { 
     return 1 
    } 

    func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int { 
     return componentArr.count 
    } 

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

回答

16

您設定選擇器視圖的數據源,但並沒有設置它的委託。

因此pickerView:titleForRow:永遠不會被調用。

+2

對於任何人想知道如何設置委託,看到這個圖片:http://static1.squarespace.com/static/52428a0ae4b0c4a5c2a2cede/t/543c1649e4b095b4c24a3d3c/1413224010678/dataSource-delegate。 png?format = 750w – scottyseus 2015-12-09 00:43:05

+0

或者添加'self.YourIBOutletForPicker.delegate = self' – 2017-11-27 03:08:27

0

您應該連接故事板中的PickerViewDatasourceDelegate或者以編程方式設置它們。看到下面的圖片。

enter image description here

0

新雨燕3已否決的上述方法使用,

我已實行以下,以使他們的工作。 (有些下劃線在參數添加

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

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

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

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) 
{ 
    /*if(row == 0) 
    { 
     self.view.backgroundColor = UIColor.whiteColor(); 
    } 
    else if(row == 1) 
    { 
     self.view.backgroundColor = UIColor.redColor(); 
    } 
    else if(row == 2) 
    { 
     self.view.backgroundColor = UIColor.greenColor(); 
    } 
    else 
    { 
     self.view.backgroundColor = UIColor.blueColor(); 
    }*/ 
}