Swift 中 UIPickerView 的自定义数据源类
Posted
技术标签:
【中文标题】Swift 中 UIPickerView 的自定义数据源类【英文标题】:Custom data source class for UIPickerView in Swift 【发布时间】:2016-03-27 16:26:37 【问题描述】:我想像这样为 UIPickerView 创建一个单独的数据源类:
class PickerData : NSObject, UIPickerViewDataSource
// class definition goes here
var pickerDataSource = ["White", "Red", "Green", "Blue"];
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int
return 1
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
return pickerDataSource.count;
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String!
return pickerDataSource[row]
当我尝试使用它时,我得到Thread 1: EXC_BAD_ACCESS ( code=1, address=0x0)
func createPickerView() -> UIView
var picker = UIPickerView(frame:CGRectMake(20, 20, 480, 20))
picker.dataSource = PickerData();
picker.delegate = self;
var newView = UIView();
newView.setTranslatesAutoresizingMaskIntoConstraints(false);
newView.backgroundColor = UIColor.whiteColor();
newView.addSubview(picker)
self.view.addSubview(newView) // <-- ERROR HERE
return newView;
但是,如果我将 dataSource 更改为 self 它可以解决问题:
picker.dataSource = self;
// and add the functions numberOfComponentsInPickerView etc to the
// main controller it works
但我不想使用self
,因为这会将代码限制为一页上只有一个 UIPickerView。也许这还不错,但感觉有点悲伤的设计。
【问题讨论】:
啊哈,函数退出后数据源变量的引用计数归零,所以必须设置为视图控制器的成员变量之类的。 【参考方案1】:是的。我认为特罗是对的。最好将数据源对象设置为视图控制器上的变量。见下文(撰写本文时为 Swift 3):
import UIKit
class MyViewController: UIViewController, UIPickerViewDelegate
var pickerDataSource = PickerData()
//...
// other properties, viewDidLoad, etc.
//...
func createPickerView() -> UIView
var picker = UIPickerView(frame: CGRect(x: 20, y: 20, width: 480, height: 20))
picker.dataSource = pickerDataSource // Data source now set to member of MyViewController
picker.delegate = self
var newView = UIView()
newView.translatesAutoresizingMaskIntoConstraints = false
newView.backgroundColor = UIColor.white
newView.addSubview(picker)
self.view.addSubview(newView)
return newView
class PickerData: NSObject, UIPickerViewDataSource
// Data source properties, initializer and methods here...
【讨论】:
以上是关于Swift 中 UIPickerView 的自定义数据源类的主要内容,如果未能解决你的问题,请参考以下文章
ios 7 中带有一个组件的自定义 UIPickerView
具有三个组件的自定义 UIPickerView,每个组件在选择指示器上显示标签