1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| import UIKit
protocol ReturnDelegate {
func DoSomething(text: String)
}
class PopoverController: UIViewController {
let picker: UIPickerView = {
let p = UIPickerView()
p.translatesAutoresizingMaskIntoConstraints = false
p.backgroundColor = .lightGray
return p
}()
let buttonOK: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("OK", for: .normal)
button.setTitleColor(.white, for: .normal)
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.white.cgColor
button.layer.cornerRadius = 10
button.addTarget(self, action: #selector(okPressed(_:)), for: .touchUpInside)
return button
}()
var delegate: ReturnDelegate!
var returnValue: String?
let dataArray = ["Test 1", "Test 2", "Test 3"]
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .lightGray
picker.delegate = self
picker.dataSource = self
self.view.addSubview(picker)
self.view.addSubview(buttonOK)
setupView(UIScreen.main.bounds.size)
}
func setupView(_ size: CGSize) {
picker.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
picker.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
picker.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
buttonOK.topAnchor.constraint(equalTo: picker.bottomAnchor, constant: 20).isActive = true
buttonOK.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 50).isActive = true
buttonOK.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -50).isActive = true
}
@objc func okPressed(_ sender: UIButton) {
if let val = returnValue {
delegate.DoSomething(text: val)
self.dismiss(animated: true, completion: nil)
}
}
}
extension PopoverController: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return dataArray.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return dataArray[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
returnValue = dataArray[row]
}
} |