我的代码bellow是一个uitextfiled,它使用一个选择器视图来显示a和b。我想要做的就是使用outlet集合为所有文本字段显示相同的选择器视图。 Textfield是单个textField,mutlipleTextifeld是我想要使用的插座集合。我只想用mutlipleTextifield替换textField。
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
let picker = UIPickerView()
let country = ["a","b"]
@IBOutlet var mutlipleTextifeld: [UITextField]!
override func viewDidLoad() {
super.viewDidLoad()
for textFieldObject in mutlipleTextifeld
{
textFieldObject.inputView = picker
}}
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return country.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return country[row]
}
public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
mutlipleTextifeld.text = country[row]
self.view.endEditing(false)
}}
答案 0 :(得分:2)
在viewDidLoad方法中使用以下代码。就是这样。!
let count : int = 0
for textField in mutlipleTextifeld {
textField.inputView = picker
textField.tag = count
count +=1
}
在控制器中使用名为textFiledTag
每当您点击文本字段时,将调用以下方法 -
textFieldDidBeginEditing
int此方法编写以下行
textFieldTag = textField.tag
现在,您可以通过获取具有全局标记值的标签来设置选择器视图的文本。
希望这会有所帮助..!
答案 1 :(得分:1)
首先将dataSource
的{{1}}和Delegate
设置为pickerView
,即self
类。我看到你没有。所以你的ViewController
会有点像这样:
viewDidLoad()
您的override func viewDidLoad() {
super.viewDidLoad()
picker.delegate = self
picker.dataSource = self
print (textFields.count)
for textFieldObject in textFields
{
textFieldObject.inputView = picker
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
将是这样的:
delegate
<强>输出强>