我正试图允许用户选择其日期的格式,以用于自定义键盘。因此,从一种观点来看,我有:
var userCustomDateArrayForSaving = []
var defaultsUser = UserDefaults(suiteName: "group.prefsettings.myapp")
和一堆带有标签的按钮,如下所示:buttons with tags
按下按钮时,它们的标签将附加到userCustomDateArrayForSaving
变量中,并且当用户按下“保存”时:
defaultsUser?.setValue(userCustomDateArrayForSaving, forKey: "dateSettings")
defaultsUser?.synchronize()
因此,最后可能等于[0, 53,52,10,52,22]
然后,在另一个视图中,我需要这样做:
var dateStampDefaults = UserDefaults(suiteName: "group.prefsettings.myapp")!.array(forKey: "dateSettings") as? [Int] ?? [Int]()
当按下日期按钮时,我一直试图在该数组上循环进行for循环并“解码”,如下所示:
@objc func myStampsDatePressed(sender: UIButton!) {
//
let date = Date()
let calendar = Calendar.current
let proxy = textDocumentProxy as UITextDocumentProxy
let formatter = DateFormatter()
var localTranslatedDateString = " "
for dateMacro in dateStampDefaults {
switch dateMacro {
case 0:
return localTranslatedDateString.append(contentsOf: (formatter.weekdaySymbols[calendar.component(.weekday, from: date)]))
case 1:
return localTranslatedDateString.append(contentsOf: (formatter.shortWeekdaySymbols[calendar.component(.weekday, from: date)]))
case 2:
return localTranslatedDateString.append(contentsOf: (formatter.veryShortWeekdaySymbols[calendar.component(.weekday, from: date)]))
case 10:
return localTranslatedDateString.append(contentsOf: (formatter.monthSymbols[calendar.component(.month, from: date)]))
case 11:
return localTranslatedDateString.append(contentsOf: (formatter.shortMonthSymbols[calendar.component(.month, from: date)]))
case 12:
return localTranslatedDateString.append(contentsOf: (formatter.veryShortMonthSymbols[calendar.component(.month, from: date)]))
...(etc)
}
let str = formatter.string(from: Date())
myStampLengthForDelete = str
proxy.insertText(localTranslatedDateString)
}
...以便某人的日期显示为“ 12月1日,星期一”。
谁能提供一些建议?谢谢!
答案 0 :(得分:0)
是的...您有一个简单的拼写错误。
defaultsUser?.setValue(userCustomDateArrayForSaving, forKey: "dateSettings")
defaultsUser?.synchronize()
var dateStampDefaults = UserDefaults(suiteName: "group.prefsettings.myapp")!.array(forKey: "dateSetting") as? [Int] ?? [Int]()
应该是
var dateStampDefaults = UserDefaults(suiteName: "group.prefsettings.myapp")!.array(forKey: "dateSettings") as? [Int] ?? [Int]() //THE last s IN dateSetting(s)
注意:
经过以下测试,并显示[0, 53, 52, 10, 52, 2]
。
var userCustomDateArrayForSaving = [0, 53,52,10,52,2]
var defaultsUser = UserDefaults(suiteName: "group.prefsettings.myapp")
defaultsUser?.setValue(userCustomDateArrayForSaving, forKey: "dateSettings")
defaultsUser?.synchronize()
var dateStampDefaults = UserDefaults(suiteName: "group.prefsettings.myapp")!.array(forKey: "dateSettings") as? [Int] ?? [Int]()
print(dateStampDefaults)