Как определить слово, нажатое в текстовом представлении из нескольких слов в SwiftUI - PullRequest
0 голосов
/ 27 апреля 2020

Я хочу отобразить список слов в режиме разметки и иметь возможность «выбрать» слово (нажмите на слово и узнайте, какое слово было нажано). Я не смог понять, как раскладывать отдельные слова плавно, поэтому я создал один Text вид со словами в виде строки, разделенной пробелом, но теперь я не знаю, как определить слово ( или ноль) включается с модификатором onTapGesture. Есть ли способ?

    @State var words : String = ["causticily", "sophora", "promiscuously", "lambaste", "pouring", "wagging", "tailblock", "coquette", "permeability", "rich", "enfilade", "centiloquy", "circumforaneous", "deturbation", "gecko", "nitro-chloroform", "migraine", "spellken", "convergence", "maggotish", "pester", "unprudent", "tenosynovitis", "yellowfish", "lionel", "turbinoid", "leased", "antitropous", "apportion", "metempsychosis", "ecchymosis", "beflower", "harns", "planetarium", "succinyl", "cremocarp", "catechisation", "capacify", "inburnt", "cabotage", "earing", "evestigate", "effectually", "balaniferous", "plowed", "angiospermatous", "acadian", "newfangly", "goblinize", "endotheca", "mesencephalon", "rose-colored", "talapoin", "academe", "cleanser", "escript", "vicine", "crossed"].joined(separator: " ")

    var body : some View {
        ZStack {
            Text(self.words)
                .lineLimit(nil)
                .onTapGesture { // (word:String?) in
                    print("word=?")
            }
        }
    }

Снимок экрана:

enter image description here

1 Ответ

0 голосов
/ 27 апреля 2020

Я адаптировал ответ @ Asperi на этот вопрос SwiftUI HStack с Wrap , который создает макет потока массива строк.

РЕДАКТИРОВАТЬ: На самом деле постукивание не работает хорошо - только первые строки слова регистрируют жест касания, и только если вы нажимаете прямо над словом. Не удалось зарегистрировать нажатие на другие строки. Действительно странно, и пахнет как ошибка.

    @State var words : [String] = ["causticily", "sophora", "promiscuously", "lambaste", "pouring", "wagging", "tailblock", "coquette", "permeability", "rich", "enfilade", "centiloquy", "circumforaneous", "deturbation", "gecko", "nitro-chloroform", "migraine", "spellken", "convergence", "maggotish", "pester", "unprudent", "tenosynovitis", "yellowfish", "lionel", "turbinoid", "leased", "antitropous", "apportion", "metempsychosis", "ecchymosis", "beflower", "harns", "planetarium", "succinyl", "cremocarp", "catechisation", "capacify", "inburnt", "cabotage", "earing", "evestigate", "effectually", "balaniferous", "plowed", "angiospermatous", "acadian", "newfangly", "goblinize", "endotheca", "mesencephalon", "rose-colored", "talapoin", "academe", "cleanser", "escript", "vicine", "crossed"]

    var body : some View {
        var width = CGFloat.zero
        var height = CGFloat.zero

        return GeometryReader { g in
            ZStack(alignment: .topLeading) {
                ForEach(0..<self.words.count, id: \.self) { i in
                    Text(self.words[i])
                        .padding([.horizontal, .vertical], 4)
                        .onTapGesture {
                            print("word tapped=\(self.words[i])")
                    }
                        .alignmentGuide(.leading, computeValue: { d in
                            if (abs(width - d.width) > g.size.width)
                            {
                                width = 0
                                height -= d.height
                            }
                            let result = width
                            if i < self.words.count-1 {
                                width -= d.width
                            } else {
                                width = 0 //last item
                            }
                            return result
                        })
                        .alignmentGuide(.top, computeValue: {d in
                            let result = height
                            if i >= self.words.count-1 {
                                height = 0 // last item
                            }
                            return result
                        })
                }
            }
        }

    }
...