gpt4 book ai didi

ios - 如何在 swift 中将值从可重用的 PickerView.xib 中传递出去

转载 作者:可可西里 更新时间:2023-11-01 01:22:55 25 4
gpt4 key购买 nike

我创建了一个可重复使用的 UIPickerView:

enter image description here

PickerView.swift:

class PickerView: UIView, UIPickerViewDelegate, UIPickerViewDataSource {

@IBOutlet weak var pickerView: UIPickerView!

var labels: [String] = [] {
didSet {
self.pickerView.reloadAllComponents()
}
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
Bundle.main.loadNibNamed("PickerView", owner: self, options: nil)
self.addSubview(pickerView)
}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return labels.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return labels[row]
}
}

这段代码使我可以通过将 UIView 的类设置为 PickerView 来初始化 UIPickerView:

enter image description here

要将数据添加到 UIPickerView,我只需创建一个 outlet 并通过该 outlet 添加数据。所以,我的 ViewController.swift 文件看起来像这样:

ViewController.swift:

class ViewController: UIViewController {

@IBOutlet weak var pickerView: PickerView!

override func viewDidLoad() {
super.viewDidLoad()
self.pickerView.labels = ["Label1","Label2","Label3"]
}
}

这是我的问题:如何将 didSelectRow 值从选择器中传递出来以在 ViewController.swift 中使用?

最佳答案

创建自定义协议(protocol)

protocol MyPickerDelegate: NSObjectProtocol {
func didSelectSomething(some: String)
}

PickerView.swift 中创建实例,例如

weak var myDelegate: MyPickerDelegate?

然后在viewDidLoad

self.pickerView.myDelegate = self

然后让你的UIViewController符合协议(protocol)

extension ViewController: MyPickerDelegate {
func didSelectSomething(some: String) {
// self.doStuff()
}
}

然后在 PickerView.swift 中调用 didSelectRow 并在其中

self.myDelegate?.didSelectSomething(some: "SomeValue")

关于ios - 如何在 swift 中将值从可重用的 PickerView.xib 中传递出去,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43074293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com