从单个 UIPicker 获取两个标签的值
Posted
技术标签:
【中文标题】从单个 UIPicker 获取两个标签的值【英文标题】:Getting values for two labels from single UIPicker 【发布时间】:2017-09-28 17:56:58 【问题描述】:尝试使用单个 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
非常感谢任何解决问题的指南
【问题讨论】:
到底是什么问题? 如何添加多个 UIPickerview 并相应地调用它们......只是一个黑客!! @Smple_V 已经做到了,但这只是为了它! @matiasofteby 有 2 个位置标签 Location1、Location2,用户可以用单个 UIPicker 填充 9 个位置。无法执行此逻辑 【参考方案1】:只需在您的选择器视图中添加一个额外的列,然后添加第二个数组来填充该新列。
这与初始化选择器视图的方法完全相同,只是增加了一些逻辑。
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
【讨论】:
只有一栏!! 你为什么要把自己限制在一个专栏里?如果您希望用户在一个选择器视图中提供两个输入,唯一合乎逻辑的事情就是提供给列。 感谢快速响应已更新代码如上以上是关于从单个 UIPicker 获取两个标签的值的主要内容,如果未能解决你的问题,请参考以下文章
从 NSArray 使用 UIPicker 获取 titleForRow - Swift