DEV Community

Lys
Lys

Posted on

3 1

Introdução ao String Catalog: Melhore a localização de strings no iOS 16 com Xcode 14

O String Catalog foi introduzido no Xcode 14, que foi lançado junto com o iOS 16. Projetado para simplificar e modernizar a forma como os desenvolvedores lidam com strings localizadas em seus projetos, ele oferece uma interface mais intuitiva e integrada em comparação aos métodos tradicionais.

Ao clicar em criar um novo arquivo, String Catalog é mostrado como opção

Image description

Ao selecionar e escolher um nome, no canto esquerdo, é mostrado os idiomas suportados, com um botão para adicionar mais opções, onde é possível adicionar português também.

Image description

Para exemplificar com código, o título dos componentes dessa Tab Bar virá do arquivo criado.

Image description

Se pensarmos que a tela está sendo criada assim

import SwiftUI

struct ContentView: View {
    var body: some View {
        TabView {
            BlogView()
                .tabItem {
                    Label("Blog",
                          systemImage: "doc.text")
                }

            InterviewGenerateQuestionsView()
                .tabItem {
                    Label("Entrevistas", systemImage: "mic.fill")
                }

            ResumeView()
                .tabItem {
                    Label("Currículo", systemImage: "book.fill")
                }

            MenuView()
                .tabItem {
                    Label("Menu", systemImage: "line.horizontal.3")
                }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Será necessária a criação de quatro propriedades que vou nomear com o sufixo title.

Image description

Caso o arquivo criado tenha o nome Localizable.strings, a string poderá ser acessada dessa forma

String(localized: "blogTitle")
Enter fullscreen mode Exit fullscreen mode

No caso de outro nome, será necessário acessar uma tabela diferente

private static func localized(_ key: String) -> String {
        return NSLocalizedString(key, 
                                 tableName: "HomeStrings", 
                                 bundle: .main, 
                                 value: "", 
                                 comment: "")
}
Enter fullscreen mode Exit fullscreen mode

Pra não sobrecarregar a função de responsabilidades e repetir código, é interessante criar um arquivo para cuidar desse acesso

import Foundation

class HomeStrings {
    static let blogTitle = localized("blogTitle")
    static let interviewTitle = localized("interviewTitle")
    static let menuTitle = localized("menuTitle")
    static let resumeTitle = localized("resumeTitle")

    private static func localized(_ key: String) -> String {
        return NSLocalizedString(key, 
                                 tableName: "HomeStrings", 
                                 bundle: .main, 
                                 value: "", 
                                 comment: "")
    }
}
Enter fullscreen mode Exit fullscreen mode

Então a ContentView ficará assim

import SwiftUI

struct ContentView: View {
    var body: some View {
        TabView {
            BlogView()
                .tabItem {
                    Label(HomeStrings.blogTitle,
                          systemImage: "doc.text")
                }

            InterviewGenerateQuestionsView()
                .tabItem {
                    Label(HomeStrings.interviewTitle,
                          systemImage: "mic.fill")
                }

            ResumeView()
                .tabItem {
                    Label(HomeStrings.resumeTitle,
                          systemImage: "book.fill")
                }

            MenuView()
                .tabItem {
                    Label(HomeStrings.menuTitle, 
                          systemImage: "line.horizontal.3")
                }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay