Установить globalVariablePicker
в методе, но НЕ в pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
Код:
import UIKit
class ProfileViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerData.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerData[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
globalVariablePicker.picked = pickerData[row]
}
struct globalVariablePicker {
static var picked = String()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
@IBOutlet weak var ProfileLabel1: UILabel!
@IBOutlet weak var ProfileLabel2: UILabel!
@IBOutlet weak var picker: UIPickerView!
@IBAction func Extend(_ sender: Any) {
print(globalVariablePicker.picked)
}
var pickerData: [String] = [String]()
override func viewDidLoad() {
super.viewDidLoad()
pickerData = ["1","2","3","4","5","6","7","8","9","10"]
self.picker.delegate = self
self.picker.dataSource = self
//Initial setup
globalVariablePicker.picked = pickerData[0] //Newline
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
ProfileLabel1.text = DetailStudentSponsoredViewController.globalVariableProfile.StringID
ProfileLabel2.text = DetailStudentSponsoredViewController.globalVariableProfile.StringName
}
}
Примечание:
Всякий раз, когда строка UIPickerView
удаляется из пула многократного использования, значение внутри него будет скопировано в globalVariablePicker
.По этой причине другое значение сохраняется в globalVariablePicker
в pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
.