Custom data source class for UIPickerView in Swift

孤者浪人 提交于 2019-12-12 00:38:39

问题


I wanted to create a separate data source class for UIPickerView like this:

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]
    }

}

When I try to use it I get 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;
}

However, if I change the dataSource to self it fixes the problem:

picker.dataSource = self; 
// and add the functions numberOfComponentsInPickerView etc to the
// main controller it works

But I would not like to use self because that limits the code to only one UIPickerView at one page. Maybe that's not so bad but it feels a bit sad design.


回答1:


Yep. I think Tero is right. It's best to have your data source object set as a variable on your view controller. See below (Swift 3 at time of writing):

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...

}


来源:https://stackoverflow.com/questions/36249752/custom-data-source-class-for-uipickerview-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!