从单个UIPicker获取两个标签的值

时间:2017-09-28 17:56:58

标签: ios swift uipickerview

enter image description here尝试使用单个UIPicker填充两个标签。它有一列,两个标签,每个标签的末尾有两个按钮。点击显示UIPicker视图

@IBOutlet weak var userLoc1: UILabel!
@IBOutlet weak var userLoc2: UILabel!

let location = ["location1", "Location2", "Location3", 
"Location4", "Location5", "Location6", "Location7"]


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

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    var countRow:Int = 0

    if pickerView == LocationPickerView{
    countRow = self.location.count
    }
    return countRow
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if pickerView == LocationPickerView
    {
    let titleLocation = location[row]
        return titleLocation
    }
    return ""
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if pickerView == LocationPickerView
    {
        selectedLocation1 = self.location[row]
        self.userLoc1.text = self.location[row]
        self.LocationPickerView.isHidden = true

 //anything that can be done here that can assign different values to 
  //two label  using the same UIPicker

    }

非常感谢任何解决问题的指南

1 个答案:

答案 0 :(得分:0)

只需在选择器视图中添加一个额外的列,然后添加第二个数组以填充该新列。

所有用于初始化pickerview的方法都只是添加了一些逻辑。

let location1 = ["location1", "Location2", "Location3", 
"Location4", "Location5", "Location6", "Location7"]

let location2 = ["location8", "Location9", "Location10", 
"Location11", "Location12", "Location13", "Location14"]

// Set number of columns in your picker view
func numberOfComponents(in pickerView: UIPickerView) -> Int {
   return 2
}

// Set number of rows of each column to length of arrays
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
   switch component {
   case 0:
      return self.location1
   case 1:
      return self.location2
   default: break
   } 
}

// Set content of rows in each column
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
   switch component {
   case 0:
      return self.location1[row]
   case 1:
      return self.location2[row]
   default: break
   } 
}


func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == LocationPickerView
{
   switch component {
   case 0:
      selectedLocation1 = self.location1[row]
      self.userLoc1.text = self.location1[row]
   case 1:
      selectedLocation2 = self.location2[row]   
      self.userLoc2.text = self.location2[row]
   default: break
   } 

   self.LocationPickerView.isHidden = true

}