func popUpList(title: String, PickerList: [String],index: Int, complistionHandler: @escaping (_ selectedValue: Int) -> ()) {
let alertController = UIAlertController(title: nil, message: "\n\n\n\n\n\n\n", preferredStyle: .alert)
alertController.isModalInPopover = true;
let picker = UIPickerView(frame: CGRect(x: 0.0, y: 0.0, width: 250, height: 250))
picker.delegate = self
picker.dataSource = self
picker.selectRow(index, inComponent: 0, animated: true)
picker.showsSelectionIndicator = true
list = PickerList
picker.reloadAllComponents()
alertController.view.addSubview(picker)
let ok = UIAlertAction(title: "Ok", style: .default) { (alert) in
print(picker.selectedRow(inComponent: 0))
complistionHandler(picker.selectedRow(inComponent: 0))
}
alertController.addAction(ok)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancel)
self.present(alertController, animated: true, completion: nil);
}
此代码始终返回值= 3.但我想获取被选中的索引值。请帮帮我
答案 0 :(得分:2)
我尝试了你的代码。事实证明你的选择器太大了,它的背景是透明的,它在你的按钮前面,所以它拦截了所有的触摸。如果减小Y尺寸,则不再发生冲突。同样,如果您添加了更多新行,则可以使用。此外,如果您将选择器发送到按钮后面,它也可以工作。如果你使用视图调试器,你可以看到选择器的范围,你可以告诉它重叠和它在按钮前面。此代码有效:
import UIKit
typealias PopUpListCompletionHandler = (Int) -> (Void)
class ViewController: UIViewController {
fileprivate var list = [String]()
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
popUpList(title: "Pick a number from 1 to 10", PickerList: stride(from: 1, to: 11, by: 1).map {"\($0)"}, index: 5) { index in
print ("You picked index \(index) which has a value of \(self.list[index])")
}
}
func popUpList(title: String, PickerList: [String],index: Int, completionHandler: @escaping PopUpListCompletionHandler) {
let alertController = UIAlertController(title: nil, message: "\n\n\n\n\n\n\n", preferredStyle: .alert)
alertController.isModalInPopover = true;
let picker = UIPickerView(frame: CGRect(x: 0.0, y: 0.0, width: 250, height: 200))
picker.delegate = self
picker.dataSource = self
picker.selectRow(index, inComponent: 0, animated: true)
picker.showsSelectionIndicator = true
list = PickerList
picker.reloadAllComponents()
alertController.view.insertSubview(picker, at: 1)
let ok = UIAlertAction(title: "Ok", style: .default) { (alert) in
completionHandler(picker.selectedRow(inComponent: 0))
self.dismiss(animated: true, completion: nil)
}
alertController.addAction(ok)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancel)
self.present(alertController, animated: true, completion: nil);
}
}
extension ViewController: UIPickerViewDelegate {
}
extension ViewController: UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return list.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return list[row]
}
}