Zhou Haibo
Zhou Haibo

Reputation: 2068

Swift: How to add localization on enum values?

I try to add localization on my app in SwiftUI, and it is working fine on pure Text("..."). But not worked on enums.

I use enum's value like below, header.name.text = HomeSection.allCases[indexPath.section].rawValue. And I did an experiment on case1 - NowPlaying, however it is not working, the text "NowPlayingSection" is showed after app is launched.

So what should I do to deal with enum on localization?

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
            switch kind {
            case UICollectionView.elementKindSectionHeader:
                guard let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: HeaderView.reuseId, for: indexPath) as? HeaderView else {
                    return UICollectionReusableView()
                }
                header.name.text = HomeSection.allCases[indexPath.section].rawValue
                header.onSeeAllClicked = { [weak self] in
                    print("%%% Click %$$$$")
                    self?.parent.seeAllforSection(HomeSection.allCases[indexPath.section])
                }
                return header
            default:
                return UICollectionReusableView()
            }
        }

Enums

enum HomeSection: String, CaseIterable {
    case NowPlaying = "NowPlayingSection"
    case Popular
    case Upcoming
    case TopActor = "Hot Actors"
}

Localizable.strings

"NowPlayingSection" = "Now playing";

Upvotes: 2

Views: 929

Answers (1)

Asperi
Asperi

Reputation: 257711

Actually what you do is not a SwiftUI part, so use with NSLocalizedString

header.name.text = 
   NSLocalizedString(HomeSection.allCases[indexPath.section].rawValue, 
       comment: "")

Upvotes: 2

Related Questions