Swift - 使用多个UIPickers查看控制器。

时间:2016-02-20 14:48:18

标签: swift viewcontroller uipicker

我使用swift 2.0(我也是Swift和iOS开发的新手)......

我想要一个有两个UIPickers的视图控制器。任何人都可以建议如何做到这一点?

我的视图控制器类......

import UIKit

class CreateSessionViewController : UIViewController, UIPickerViewDataSource,UIPickerViewDelegate {

//Outlets:
@IBOutlet var durationPicker: UIPickerView!
@IBOutlet var typePicker: UIPickerView!

//Dummy duration array:
var durationArray = ["10", "20", "30", "40", "50", "60"];

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

    self.durationPicker.dataSource = self;
    self.durationPicker.delegate = self;

}

//Picker view methods:
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

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

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

}

现在,durationPicker运行良好,但我如何填充typePicker?

2 个答案:

答案 0 :(得分:2)

您应该使用传递给每个委托方法的pickerView对象:

//Picker view methods:
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
  if pickerView == durationPicker {
    return 1
  } else if pickerView == typePicker {
    return 2
  }

  return 0
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
  if pickerView == durationPicker {
    return durationArray.count
  } else if pickerView == typePicker {
    return typeArray.count
  }

  return 0
}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
  if pickerView == durationPicker {
    return durationArray[row]
  } else if pickerView == typePicker {
    return typeArray[row]
  }

  return nil
}

答案 1 :(得分:1)

您需要像这样

过滤委托方法
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    if durationPicker == pickerView {
        return 1 // The amount that you need for the durationPicker
    } else if typePicker == pickerView {
        return 2 // The amount that you need for the typePicker
    }

}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    if durationPicker == pickerView {
        return durationArray.count 
    } else if typePicker == pickerView {
        return typeArray.count
    }
}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if durationPicker == pickerView {
        return durationArray[row]
    } else if typePicker == pickerView {
        return typeArray[row]
    }
}

希望这对你有帮助!