如何在Swift 3中的PickerView中设置行的标题?

时间:2017-08-18 09:02:41

标签: ios

我需要根据数组为行提供标题,但我不知道如何执行此操作。我是iOS新手。

class ViewController: UIViewController , UIPickerViewDelegate, UIPickerViewDataSource{

    @IBOutlet weak var pickerView: UIPickerView!
    @IBOutlet weak var label: UILabel!
    var names: Array<String>?
    var department: Array<String>?
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        names = ["Vineeta", "Shubham" ,"Anand", "Vivek", "Akshay", "Harshit", "Vikas", "Prasoon", "Sunil"]
        department = ["iOS","Angular", ".Net", "iOS","iOS", ".Net", "Android","Android", "Angular"]
    }

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

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 2
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return 9
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if component == 0 {
            [names o]
        }
    }


}

2 个答案:

答案 0 :(得分:1)

不要忘记UIPickerViewDelegate,UIPickerViewDataSource

@IBOutlet弱变量选择器:UIPickerView!

override func viewDidLoad() {
        super.viewDidLoad()
        pickerData = ["X","Y"]
        picker.delegate = self
        picker.dataSource = self

    }


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

        func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            return pickerData.count
        }
        func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            return pickerData[row]
        }
        func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
           let selectedText = pickerData[row]
        }

答案 1 :(得分:0)

使用此代码 -

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
    if component == 0
    {
        return names?.count
    }
    else
    {
        return department?.count
    }
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{
    if component == 0
    {
        return names?[row]
    }
    else
    {
        return department?[row]
    }
}