Search code examples
iosiphoneswift

How to display Localized days of the week in CollectionView in Swift? iOS


I was just making a weather app that displays 5-day weather temperatures. And the problem that I have right now is how do I display weekdays that are retrieved dynamically on my Collection View? They are well displaying in English, but I want them to be in Russian. The source is given below:

This is the code that is in my cellForItemAt function

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

This is my Localizable.string file:

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

Please let me know if you need any other source or answer. Any help will be very appreciated!


Solution

  • Your Localized.string file should be

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

    and

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

    Update for displaying "Today" as current day

    Create Extension+Date.swift file first. Add code below into the file.

    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
            }
    }
    

    At your cellForRow modify to:

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

    Add Today key in your Localized.string file

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