如何填充" ArrayYear"在选择器视图?

时间:2016-03-05 02:33:43

标签: ios arrays swift uipickerview

import UIKit

class SecondViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

//UI TextFields
@IBOutlet weak var ChassisText: UITextField!

@IBOutlet weak var YearFromText: UITextField!

@IBOutlet weak var YearToText: UITextField!

@IBOutlet weak var MakeText: UITextField!

@IBOutlet weak var ModelText: UITextField!

//Used Variables
var YearFrom:String = "0"
var YearTo:String = "2020"
var ChassisNumber:String = ""
var ArrayYear:[String] = [""]
var ArrayMake = [String]()
var ArrayModel = [String]()
var i:Int = 0
var holdSelect = 0
//UIPickerView
var pickerselection: UIPickerView!

//Boolean Variables
var checkYearFrom: Bool = false
var checkYearTo: Bool = false
var checkMake: Bool = false
var checkModel: Bool = false

//Picker Actions
func DonePicker()
{
    if checkYearFrom {
        YearFromText.text = "\(ArrayYear[holdSelect])"
        YearFrom = "\(ArrayYear[holdSelect])"
        YearFromText.resignFirstResponder()
        checkYearFrom = false
    }
    else if checkYearTo {
        YearToText.text = "\(ArrayYear[holdSelect])"
        YearTo = "\(ArrayYear[holdSelect])"
        YearToText.resignFirstResponder()
        checkYearTo = false
    }
}
func CancelPicker()
{
    YearFromText.resignFirstResponder()
    YearToText.resignFirstResponder()
    ModelText.resignFirstResponder()
    MakeText.resignFirstResponder()
}

//Picker View Functions
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{
    if checkYearFrom || checkYearTo {
        return ArrayYear[row]
    }
    else
    {
        return ArrayYear[row]
    }
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
    if checkYearFrom || checkYearTo {
        return ArrayYear.count
    }
    else
    {
    return ArrayYear.count
    }
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int
{
    return 1
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
    holdSelect = row
    pickerView.reloadAllComponents()
}

}

我上面的代码以编程方式创建了选择器视图,还有取消和完成的buttonItem。

这行代码是我创建Year Array的地方:

var YearFrom:String = "0"
var YearTo:String = "2020"
var ArrayYear:[String] = [""]
var i:Int = 0

在viewDidLoad上,这是为年份创建for循环的地方:

    for var index = 1980; index <= 2016; index++ {
        ArrayYear.insert("\(index)", atIndex: i)
    }

    i = 0

    //Creating Picker Programatically
    pickerselection = UIPickerView(frame: CGRectMake(0, 200, view.frame.width, 300))
    pickerselection.backgroundColor = .whiteColor()
    pickerselection.showsSelectionIndicator = true
    pickerselection.delegate = self
    pickerselection.dataSource = self

在运行阶段,我在&#39; YearFromText&#39;上测试选择器视图。我创建的数组没有显示(1980 - 2016)。

ArrayYear的实现是否有问题。

我是快速编程的新手。

1 个答案:

答案 0 :(得分:1)

如果您只想要数组中的年份,那么您可以简单地执行此操作:

let years = (1980...2016).map { String($0) }