SwiftUI текстовый подтекст - PullRequest
1 голос
/ 07 января 2020

Есть ли какой-нибудь способ в SwiftUI открыть браузер при нажатии на некоторую часть текста.

Я пробовал вышеуказанное решение, но оно не работает, потому что onTapGesture возвращает View, что вы не можете добавить к Text

Text("Some text ").foregroundColor(Color(UIColor.systemGray)) +
Text("clickable subtext")
   .foregroundColor(Color(UIColor.systemBlue))
   .onTapGesture {

   }

Я хочу, чтобы в главном тексте был текст с возможностью вставки, поэтому использование HStack не будет работать

1 Ответ

3 голосов

К сожалению, в SwiftUI нет ничего похожего на NSAttributedString. И у вас есть только несколько вариантов. В этом ответе вы можете увидеть, как использовать UIViewRepresentable для создания старой школы UILabel с событием щелчка , например. Но теперь единственный способ SwiftUI - использовать HStack:

struct TappablePieceOfText: View {

    var body: some View {

        HStack(spacing: 0) {
            Text("Go to ")
                .foregroundColor(.gray)

            Text("stack overflow")
                .foregroundColor(.blue)
                .underline()
                .onTapGesture {
                    let url = URL.init(string: "https://stackoverflow.com/")
                    guard let stackOverflowURL = url, UIApplication.shared.canOpenURL(stackOverflowURL) else { return }
                    UIApplication.shared.open(stackOverflowURL)
                }

            Text(" and enjoy")
                .foregroundColor(.gray)
        }


    }
}

ОБНОВЛЕНИЕ Добавлено решение с UITextView и UIViewRepresentable. Я объединил все из добавленных ссылок, и результат довольно хороший, я думаю:

import SwiftUI
import UIKit

struct TappablePieceOfText: View {

    var body: some View {
        TextLabelWithHyperlink()
            .frame(width: 300, height: 110)
    }

}

struct TextLabelWithHyperlink: UIViewRepresentable {

    func makeUIView(context: Context) -> UITextView {

        let standartTextAttributes: [NSAttributedString.Key : Any] = [
            NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20),
            NSAttributedString.Key.foregroundColor: UIColor.gray
        ]

        let attributedText = NSMutableAttributedString(string: "You can go to ")
        attributedText.addAttributes(standartTextAttributes, range: attributedText.range) // check extention

        let hyperlinkTextAttributes: [NSAttributedString.Key : Any] = [
            NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20),
            NSAttributedString.Key.foregroundColor: UIColor.blue,
            NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue,
            NSAttributedString.Key.link: "https://stackoverflow.com"
        ]

        let textWithHyperlink = NSMutableAttributedString(string: "stack overflow site")
        textWithHyperlink.addAttributes(hyperlinkTextAttributes, range: textWithHyperlink.range)
        attributedText.append(textWithHyperlink)

        let endOfAttrString = NSMutableAttributedString(string: " end enjoy it using old-school UITextView and UIViewRepresentable")
        endOfAttrString.addAttributes(standartTextAttributes, range: endOfAttrString.range)
        attributedText.append(endOfAttrString)

        let textView = UITextView()
        textView.attributedText = attributedText

        textView.isEditable = false
        textView.textAlignment = .center
        textView.isSelectable = true

        return textView
    }

    func updateUIView(_ uiView: UITextView, context: Context) {}

}

результат HStack и Text: imageHStack and Text">

результат UIViewRepresentable и UITextView:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...