如何制作一个包含当前月份和接下来几个月的数组。

时间:2017-10-09 17:19:14

标签: arrays swift uipickerview

我正在制作一年中所有月份的pickerView,我想在pickerView的开头和接下来的月份创建一个当前月份的数组,依此类推。我已经在所有月份填充了pickerView和数组,我也得到了当前的日期。

let Months = ["January","Febrary","March","April","May","June","July","August","September","October","November","December"]

@IBOutlet var DateLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    DateTime()
}

func DateTime() {

    let time = DateFormatter ()
    let date = DateFormatter ()

    time.timeStyle = .medium
    date.dateStyle = .full

    print(time.string(from: Date()))
    print(date.string(from: Date()))

    //RiderTimeStampRequested = time.string(from: Date())
    DateLabel.text = date.string(from: Date())
}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return Months.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
     return Months[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
     print(Months[row])
}

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您希望获得当月之后所有月份的数组,包括当前月份。如果它是7月份,那么您的数组将包含:

["July", "August", "September", "October", "November", "December"]

为此,我们可以使用dropFirst方法删除数组的前x个元素。

您可以声明这样的新属性:

var monthsInPickerView: [String]!

然后在viewDidLoad中初始化它:

let calendar = Calendar.current
let month = calendar.dateComponents([.month], from: Date()).month!
monthsInPickerView = Array(Months.dropFirst(month - 1))

然后您会使用monthsInPickerView作为选择器视图的数据源。