我知道这是一个微不足道的错误,但我无法解决这个问题而且我被卡住了。
我想分配给UISegmentedControl(有6个段)第一个段中的当前日期和下一个段中的后续5天日期,如下图所示。为此,我需要构建一个从日期开始的字符串数组,但是我在此行let dayString = dateFormatter.shortWeekdaySymbols[dayComponent-1]
var stringDates = [String]()
override func viewDidLoad() {
super.viewDidLoad()
//for each segment, construct a string date with the currentDate() being first
for i in 1...6 {
let dateFormatter = DateFormatter()
let today = Date()
let calendar = Calendar.current
if i == 1 {
let dayComponent = Calendar.current.component(.day,from: today)
let dayString = dateFormatter.shortWeekdaySymbols[dayComponent-1]
let month = Calendar.current.component(.month, from: today)
let monthSymbol = dateFormatter.shortMonthSymbols[month-1]
let dayMonthString = dayString + monthSymbol
stringDates.append(dayMonthString)
} else {
var components = DateComponents()
components.weekday = i
let nextDay = calendar.date(byAdding: components, to: today)
let dayComponent = Calendar.current.component(.day,from: nextDay!)
let dayString = dateFormatter.shortWeekdaySymbols[dayComponent-1]
let month = Calendar.current.component(.month, from: nextDay!)
let monthSymbol = dateFormatter.shortMonthSymbols[month-1]
let dayMonthString = dayString + monthSymbol
stringDates.append(dayMonthString)
}
}
}
答案 0 :(得分:1)
而不是.day
let dayComponent = Calendar.current.component(.day,from: today)
使用.weekday
,如下所示:
let today = Date()
let dateFormatter = DateFormatter()
let dayComponent = Calendar.current.component(.weekday,from: today)
let dayString = dateFormatter.shortWeekdaySymbols[dayComponent - 1] //Fri
答案 1 :(得分:1)
崩溃的原因是shortWeekdaySymbols []只能采用0到6之间的值。
shortWeekdaySymbols[0] = sun
shortWeekdaySymbols[1] = mon
等等。
let stringArray = [String]()
for value in 1 ..< 6 {
let today = Date()
let tomrow = Calendar.current.date(byAdding: .day, value: value, to:today)
let dateFormatter = DateFormatter()
let dayComponent = Calendar.current.component(.weekday,from: tomrow!)
let day = Calendar.current.component(.day, from: tomrow!)
let month = Calendar.current.component(.month, from: tomrow!)
let dayString = dateFormatter.shortWeekdaySymbols[dayComponent - 1]
let monthString = (dateFormatter.shortStandaloneMonthSymbols[month - 1])
let FullDate = String(day) + " " + monthString + " " + dayString
print(FullDate)
}