我有DrinkVolumePickerController.swift
我试图保留委托和数据源逻辑以使它们远离我的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()
}
}
当我在模拟器中运行时,我没有看到Picker,但我可以在DebugViewHeirarchy中看到它。
如果我将所有逻辑移回ViewController并将delegate
和datasource
更改为self
,那么它会正常加载。
我只是不明白为什么它不能在外部文件中使用它们?
答案 0 :(得分:0)
您遇到了内存管理问题。
移动线:
let controller = DrinkVolumePickerController()
是AddDrinkViewController
的属性,而不是drinkVolumeControl
内的局部变量。