向下滚动选取器视图时崩溃

时间:2015-10-17 17:12:09

标签: ios swift uipickerview

我正在建立一个"日期" UiPickerView能够自定义字体大小,类型和颜色。

请参阅我的代码。

{

    @IBOutlet weak var dataInicio: UIPickerView!

    var dataDia1: NSMutableArray!
    var dataMes1: NSArray!
    var dataAno1: NSMutableArray!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        self.dataDia1 = NSMutableArray()

        for dia in 1...31
        {
            dataDia1.addObject("\(dia)")
        }

        self.dataMes1 = NSArray(objects: "Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro")

        self.dataAno1 = NSMutableArray()

        for ano in 1970...2016
        {
            dataAno1.addObject("\(ano)")
        }


    }

    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int
    {
        return 3
    }

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
    {
        if (component == 0)
        {
            return dataDia1.count
        }

        if (component == 1)
        {
            return dataMes1.count
        }

        else
        {
            return dataAno1.count
        }
    }

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
    {
        var componentStr = dataDia1[row]

        if(component == 0)
        {
            return componentStr as? String
        }

        if(component == 1)
        {
            componentStr = (dataMes1[row] as? String)!
            return componentStr as? String

        }
        else
        {
            componentStr = (dataAno1[row] as? String)!
            return componentStr as? String
        }
    }

}

它的构建成功,但是当我向下滚动年份时,当阵列中有超过27个组件时,它会崩溃。

我发起这个并且我已经环顾网络并没有找到任何结果。 :(

我做错了什么?

1 个答案:

答案 0 :(得分:0)

无论要求哪个组件,都可以致电var componentStr = dataDia1[row]。将您的代码更改为:

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{
    if(component == 0)
    {
        var componentStr = dataDia1[row]
        return componentStr as? String
    }
    else if(component == 1)
    {
        var componentStr = (dataMes1[row] as? String)!
        return componentStr as? String

    }
    else
    {
        var componentStr = (dataAno1[row] as? String)!
        return componentStr as? String
    }
}

另请注意使用else if