如何在Swift中的CollectionView中显示本地化的星期几?iOS

f0ofjuux  于 12个月前  发布在  Swift
关注(0)|答案(2)|浏览(151)

我只是做了一个天气应用程序,显示5天的天气温度。我现在的问题是**我如何显示在我的收藏视图动态检索的工作日?**他们是很好地显示在英语中,但我希望他们是在俄罗斯。源代码如下:

这是我的cellForItemAt函数中的代码

dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.setLocalizedDateFormatFromTemplate("EEEE")
let actualDate = dateFormatter.string(from: date)
cell.dayCollection.text = String(NSLocalizedString("%@", comment: "displaying weekdays"), actualDate) // see this line
return cell

字符串

这是我的Localizable.string文件:

"%@" = "Воскресенье";
"%@" = "Понедельник";
"%@" = "Вторник";
"%@" = "Среда";
"%@" = "Четверг";
"%@" = "Пятница";
"%@" = "Суббота";


请让我知道如果你需要任何其他来源或答案。任何帮助将非常感谢!

wztqucjr

wztqucjr1#

我认为最好使用默认的日期本地化,而不是自定义的本地化字符串。

let date = Date() 
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "ru_RU")
dateFormatter.dateFormat = "EEEE"
let day = dateFormatter.string(from: date).capitalized
print(day)  // you will see eg. "Пятница"

字符串
您甚至可以使用Locale.current,日期将根据用户的设备语言显示。

brgchamk

brgchamk2#

您的Localized.string文件应该是

"Sunday" = "Воскресенье";
"Monday" = "Понедельник";
"Tuesday" = "Вторник";
"Wednesday" = "Среда";
"Thursday" = "Четверг";
"Friday" = "Пятница";
"Saturday" = "Суббота";

字符串

let day = NSLocalizedString(actualDate, comment: "")
cell.dayCollection.text = day

更新显示“今天”为当前日期

首先创建Extension+Date.swift文件。将下面的代码添加到文件中。

extension Date {
        /// Compare self with another date.
        ///
        /// - Parameter anotherDate: The another date to compare as Date.
        /// - Returns: Returns true if is same day, otherwise false.
        public func isSame(_ anotherDate: Date) -> Bool {
            let calendar = Calendar.autoupdatingCurrent
            let componentsSelf = calendar.dateComponents([.year, .month, .day], from: self)
            let componentsAnotherDate = calendar.dateComponents([.year, .month, .day], from: anotherDate)
            
            return componentsSelf.year == componentsAnotherDate.year && componentsSelf.month == componentsAnotherDate.month && componentsSelf.day == componentsAnotherDate.day
        }
}


在您的cellForRow修改为:

var actualDate = dateFormatter.string(from: date)
if date.isSame(Date()) {
    actualDate = "Today"
}


Localized.string文件中添加Today密钥

"Today" = "Cегодня";

相关问题