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

问题描述 投票:0回答:2

我正在制作一个显示 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

这是我的 Localized.string 文件:

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

如果您需要任何其他来源或答案,请告诉我。任何帮助将不胜感激!

ios iphone swift
2个回答
5
投票

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

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
并且会显示天数 根据用户的设备语言。


2
投票

您的

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" }
在您的 

Today

 文件中添加 
Localized.string
 密钥

"Today" = "Cегодня";
    
© www.soinside.com 2019 - 2024. All rights reserved.