ryanlintott / FrameUp

Reframing SwiftUI Views. A collection of tools to help with layout.
MIT License
196 stars 4 forks source link

Justified Attributed String #7

Closed waelsaad closed 1 year ago

waelsaad commented 1 year ago

Hi Ryan :)

Thank you for all of your respones. This is my last challange that I am currently working on. I am a bit confused about how to solve.

The getText function returns an AttributedString. In the sentense I am passing it has some couple of words that are in a different language so its using its own font with a different color. In a normal SwiftUI Text view my AttributedString appears correctly.

I understand why the attributes get lost as I am converting the attributed string back to a string to extract the words but how can I maintain the attributes for every word? Thanks.

I think its probablly this line it needs to return an AttributedString !

let words = Array(text.string.split(separator: " ").map(String.init).enumerated())

extension AttributedString {
    var string: String {
        String(self.characters)
    }
}
    @ViewBuilder
    func justifiedItem(_ item: TextItem, _ language: LanguageType) -> some View {
        if let text = viewModel.getText(item, language) {
            let words = Array(text.string.split(separator: " ").map(String.init).enumerated())
                HFlowLayout(alignment: .justified) {
                    ForEach(words, id: \.offset) { word in
                        Text(word.element)
                            .foregroundColor(viewModel.color(item))
                            .font(Font(viewModel.font(item, language)))
                    }
                }
        }
    }
waelsaad commented 1 year ago

Nevermind. It was some NSAttributedString manipulation. Thank you :)