gpt4 book ai didi

ios - UIPickerView 未出现

转载 作者:行者123 更新时间:2023-11-30 11:27:56 25 4
gpt4 key购买 nike

我有 DrinkVolumePickerController.swift ,我试图在其中保留委托(delegate)和数据源逻辑,以使它们远离我的 ViewController

import UIKit

class DrinkVolumePickerController: NSObject, UIPickerViewDelegate, UIPickerViewDataSource {

var quantities: [(label: String, ml: Int)] = [("Pint", 568), ("Can", 330)]

func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return quantities.count
}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return quantities[row].label + " - " + String(quantities[row].ml)
}

}

在我的 ViewController 中我有

import UIKit

class AddDrinkViewController: UIViewController {

lazy var drinkVolumeControl: UIPickerView! = {
let view = UIPickerView()
view.translatesAutoresizingMaskIntoConstraints = false

let controller = DrinkVolumePickerController()
view.delegate = controller
view.dataSource = controller

return view
}()

override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(drinkVolumeControl)
view.setNeedsUpdateConstraints()
}
}

当我在模拟器中运行它时,我看不到选取器,但我可以在 DebugViewHeirarchy 中看到它。

如果我将所有逻辑移回 ViewController 并将 delegatedatasource 更改为 self,那么它会正常加载。

我只是不明白为什么将它们放在外部文件中不起作用?

最佳答案

您遇到内存管理问题。

移动线:

let controller = DrinkVolumePickerController()

成为 AddDrinkViewController 的属性,而不是 drinkVolumeControl 内的局部变量。

关于ios - UIPickerView 未出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50547537/

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