https://kotlinlang.org logo
#moko
Title
d

Darron Schall

06/28/2023, 1:44 PM
I've been using moko-resources, and made some SwiftUI extensions that make integration easier. Thought I'd share them here. I'll put them in a thread to keep the channel cleaner.
Copy code
extension StringResource {
    func localized() -> String {
        return desc().localized()
    }
}

extension Image {
    init(resourceKey: KeyPath<MR.images, ImageResource>) {
        self.init(uiImage: MR.images()[keyPath: resourceKey].toUIImage()!)
    }
}

extension Text {
    init(resourceKey: KeyPath<MR.strings, StringResource>) {
        self.init(MR.strings()[keyPath: resourceKey].localized())
    }
}

extension Button where Label == Text {
    init(resourceKey: KeyPath<MR.strings, StringResource>, action: @escaping () -> Void) {
        self.init(MR.strings()[keyPath: resourceKey].localized(), action: action)
    }
    
    init(resourceKey: KeyPath<MR.strings, StringResource>, role: ButtonRole?, action: @escaping () -> Void) {
        self.init(MR.strings()[keyPath: resourceKey].localized(), role: role, action: action)
    }
}
This makes the SwiftUI read nicely, allowing you to just reference the keys, like this:
Copy code
Image(resourceKey: \.logo)
Copy code
Button(resourceKey: \.menu__logout, role: .destructive) {
    viewModel.logout()
}
Copy code
Text(resourceKey: \.welcome__body)
I did add the Image extension to the README already. I considered adding the others, but wasn't sure.
a

alex009

06/28/2023, 3:59 PM
cool! can you create issue on github with this? like "SwiftUI extensions for better integration". maybe we add some cocoapods addition for this extensions or some tool for kotlin/native will be released and give us chance to distribute swift additions for kotlin libs
👍 1
d

Darron Schall

06/28/2023, 5:00 PM