Swift中UIPickerView的自定义数据源类

时间:2016-03-27 16:26:37

标签: ios swift uiview uipickerview

我想为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 个答案:

答案 0 :(得分:1)

是的。我认为Tero是对的。最好将数据源对象设置为视图控制器上的变量。见下文(撰写本文时的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...

}