Xcode 11;斯威夫特4
如何在同一控制器上使用2个UIPicker?
例如,在下面的代码中,我想简单比较UIPicker 1的值和UIPicker2的值。谢谢!
应该是这样的:
这是我的示例:
if row1 == 0 && row2 == 0 {
}
else if row1 == 0 && row2 == 1 {
}
else {
}
真实代码:
import Foundation
import UIKit
var data1 = ["1", "2", "3", "4", "5"]
var data2 = ["1", "2", "3", "4", "5"]
var Calculator = "0"
class ThirdViewController: UIViewController, UIScrollViewDelegate, UIPickerViewDataSource, UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return data1.count
}
func pickerView(_ pickerView: UIPickerView,
titleForRow row: Int,
forComponent component: Int) -> String? {
return data1[row]
}
@IBOutlet weak var Calculator: UILabel!
@IBOutlet weak var from: UIPickerView!
@IBOutlet weak var to: UIPickerView!
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if row == 0 {
} else if row == 1 {
} else if row == 2 {
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.from.dataSource = self
self.from.delegate = self
self.to.dataSource = self
self.to.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
答案 0 :(得分:4)
您可以像这样使用sth:
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == from {
return data1.count
} else {
return data2.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == from {
return data1[row]
} else {
return data2[row]
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let index1 = from.selectedRow(inComponent: 0)
let index2 = to.selectedRow(inComponent: 0)
let row1 = data1[index1]
let row2 = data2[index2]
calculator.text = "\(row1) - \(row2)"
}
任何UIKit委托函数都将接收调用组件作为第一个参数,您可以使用该参数来检查哪个组件正在执行该函数。
答案 1 :(得分:1)
为什么不设置每个选择器标签值,并使用该值来标识每个选择器标签,如下所示:
首先为每个选择器设置标签值
override func viewDidLoad() {
super.viewDidLoad()
self.from.dataSource = self
self.from.delegate = self
self.from.tag = 1
self.to.dataSource = self
self.to.delegate = self
self.to.tag = 2
}
然后使用该标记值标识每个选择器:
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView.tag == 1 {
return data1[row]
} else {
return data2[row]
}
}