Swift中的UIPickerView子类:viewForRow中的错误可选值

时间:2015-02-19 16:33:24

标签: ios swift datepicker uipickerview

我想继承UIPickerView以创建自定义DatePicker。我试过这个,但Swift说错误:

  

在解包可选值时意外发现nil

就在这一行:(view.viewWithTag(1) as UILabel).text = array[row]

以下是代码:

class MyPickerView : UIPickerView, UIPickerViewDataSource, UIPickerViewDelegate{

    let array = ["one", "two", "three"]
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect) {
        super.init(frame:frame)
        self.delegate = self
        self.dataSource = self
    }

    //components / row
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return array.count
    }

    //view for row
    func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView {
        if view == nil {
            var view = UIView(frame: CGRectMake(0,0, 150,50))
            let label = UILabel(frame:CGRectMake(0,0, 80, 40))
            label.tag = 1
            view.addSubview(label)
        }
        (view.viewWithTag(1) as UILabel).text = array[row]
        return view
    }
    //did select row
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        println("has selected row \(row)")
    }

由于

2 个答案:

答案 0 :(得分:3)

UIPickerView中存在一个已知的错误(我认为在iOS 7中启动),视图永远不会被重用。要解决您的问题,请删除if子句(然后不需要标记),

func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView {
    var view = UIView(frame: CGRectMake(0,0, 150,50))
    let label = UILabel(frame:CGRectMake(0,0, 80, 40))
    view.addSubview(label)
    label.text = array[row]
    return view
}

您收到错误的原因是因为您有两个名为“view”的不同对象。你在if子句中创建的那个在子句之外是不可见的,所以你正在调用viewWithTag的“视图”是传递给方法的视图,并且那个视图总是为零。

答案 1 :(得分:1)

首先检查视图是否为零,但是在关闭之后,您尝试访问它,无论它是否为零。如果我理解你的意图,你应该替换

var view = UIView(frame: CGRectMake(0,0, 150,50))

view = UIView(frame: CGRectMake(0,0, 150,50))

因为目前你正在if语句的范围内创建一个名为view的新变量。