【问题标题】:SwiftUI tappable subtextSwiftUI 可点击的潜台词
【发布时间】:2020-04-24 17:58:02
【问题描述】:

当点击文本的某些部分时,SwiftUI 中有什么方法可以打开浏览器。

我尝试了上述解决方案,但它不起作用,因为 onTapGesture 返回您无法添加到 Text 的 View

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

   }

我想在正文中有可点击的潜台词,这就是为什么使用 HStack 不起作用的原因

【问题讨论】:

    标签: ios swift xcode text swiftui


    【解决方案1】:

    适用于 iOS 15 及更高版本的更新: 对Text 有新的Markdown 格式支持,如:

    Text("Some text [clickable subtext](some url) *italic ending* ")
    

    详情可查看WWDC session with a timecode

    iOS 13 和 14 的旧答案:

    不幸的是,SwiftUI 中没有任何类似于 NSAttributedString 的东西。你只有几个选择。 In this answer 你可以看到如何使用UIViewRepresentable 来创建一个老式的UILabel with click event,例如。但是now the only SwiftUI way是用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 的结果:

    UIViewRepresentable 和 UITextView 的结果:

    更新 2: 这是一个NSMutableAttributedString 的小扩展:

    extension NSMutableAttributedString {
        
        var range: NSRange {
            NSRange(location: 0, length: self.length)
        }
        
    }
    

    【讨论】:

    • 感谢您的回答,此解决方案非常适用于单行文本,但对于多行文本似乎没有 SwiftUI 的做法。
    • @KarenKarapetyan,使用UIViewRepresentable 和UITextView 检查更新。我想我会在我的项目中使用它,因为我没有找到更好的解决方案
    • @АлександрГрабовский 嗨,扩展名是什么?没有在答案中看到。谢谢!
    • 您使用的.range 扩展名是什么?我收到一个错误,Value of type 'NSMutableAttributedString' has no member 'range'。
    • @Zorayr 检查最后的 UPDATE 2
    【解决方案2】:

    我没有耐心让UITextView 和UIViewRepresentable 工作,所以我将整个段落设为可点击,但仍保留下划线的URL 外观/感觉。如果您尝试将服务条款 URL 链接添加到您的应用,则特别有用。

    代码相当简单:

    Button(action: {
        let tosURL = URL.init(string: "https://www.google.com")! // add your link here
        if UIApplication.shared.canOpenURL(tosURL) {
            UIApplication.shared.open(tosURL)
        }
    }, label: {
        (Text("Store.ly helps you find storage units nearby. By continuing, you agree to our ")
            + Text("Terms of Service.")
                .underline()
            )
            .frame(maxWidth: .infinity, alignment: .leading)
            .font(Font.system(size: 14, weight: .medium))
            .foregroundColor(Color.black)
            .fixedSize(horizontal: false, vertical: true)
    })
        .padding([.horizontal], 20)
    
    

    【讨论】:

    • 感谢@Zorayr 的回答,这个解决方案也可能对某人有用。
    【解决方案3】:

    基于 Dhaval Bera 的代码,我放了一些结构体。

    struct TextLabelWithHyperLink: UIViewRepresentable {
      
      @State var tintColor: UIColor
      
      @State var hyperLinkItems: Set<HyperLinkItem>
      
      private var _attributedString: NSMutableAttributedString
      
      private var openLink: (HyperLinkItem) -> Void
      
      init (
        tintColor: UIColor,
        string: String,
        attributes: [NSAttributedString.Key : Any],
        hyperLinkItems: Set<HyperLinkItem>,
        openLink: @escaping (HyperLinkItem) -> Void
      ) {
        self.tintColor = tintColor
        self.hyperLinkItems = hyperLinkItems
        self._attributedString = NSMutableAttributedString(
          string: string,
          attributes: attributes
        )
        self.openLink = openLink
      }
      
      
      func makeUIView(context: Context) -> UITextView {
        let textView = UITextView()
        textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        textView.isEditable = false
        textView.isSelectable = true
        textView.tintColor = self.tintColor
        textView.delegate = context.coordinator
        textView.isScrollEnabled = false
        return textView
      }
      
      func updateUIView(_ uiView: UITextView, context: Context) {
       
        for item in hyperLinkItems {
          let subText = item.subText
          let link = item.subText.replacingOccurrences(of: " ", with: "_")
          
          _attributedString
            .addAttribute(
              .link,
              value: String(format: "https://%@", link),
              range: (_attributedString.string as NSString).range(of: subText)
            )
        }
        
        uiView.attributedText = _attributedString
      }
      
      func makeCoordinator() -> Coordinator {
        Coordinator(parent: self)
      }
      
      class Coordinator: NSObject, UITextViewDelegate {
        var parent : TextLabelWithHyperLink
        
        init( parent: TextLabelWithHyperLink ) {
          self.parent = parent
        }
        
        func textView(
          _ textView: UITextView,
          shouldInteractWith URL: URL,
          in characterRange: NSRange,
          interaction: UITextItemInteraction
        ) -> Bool {
          
          let strPlain = URL.absoluteString
            .replacingOccurrences(of: "https://", with: "")
            .replacingOccurrences(of: "_", with: " ")
          
          if let ret = parent.hyperLinkItems.first(where: { $0.subText == strPlain }) {
            parent.openLink(ret)
          }
          
          return false
        }
      }
    }
    
    struct HyperLinkItem: Hashable {
        
      let subText : String
      let attributes : [NSAttributedString.Key : Any]?
      
      init (
        subText: String,
        attributes: [NSAttributedString.Key : Any]? = nil
      ) {
        self.subText = subText
        self.attributes = attributes
      }
      
      func hash(into hasher: inout Hasher) {
        hasher.combine(subText)
      }
        
      static func == (lhs: HyperLinkItem, rhs: HyperLinkItem) -> Bool {
        lhs.hashValue == rhs.hashValue
      }
    }
    

    用法:

    
    TextLabelWithHyperLink(
      tintColor: .green,
      string: "Please contact us by filling contact form. We will contact with you shortly.  Your request will be processed in accordance with the Terms of Use and Privacy Policy.",
      attributes: [:],
      hyperLinkItems: [
        .init(subText: "processed"),
        .init(subText: "Terms of Use"),
      ],
      openLink: {
      (tappedItem) in
        print("Tapped link: \(tappedItem.subText)")
      }
    )
    

    【讨论】:

      【解决方案4】:

      我使用了@АлександрГрабовский 的答案,但我还必须进行一些配置才能使其适合我。 我的文本字段中有 2 个链接,它们都有自定义颜色并将用户引导到不同的页面。 我也不希望启用滚动,但如果我禁用它,高度不会得到调整,它会延伸到视图的外部。 我尝试了很多不同的方法,目前我发现了一个适合我的解决方案,所以我想我不妨在这里分享一下。

      再次感谢@АлександрГрабовский 的回答,我设法做到了。我唯一需要做的调整是:

      1. 将与文本颜色相关的链接属性设置为另一个 var,并将 UITextView 上的“linkTextAttributes”属性设置为该属性,以更改文本颜色,而字体和链接目标我使用了他在回复中建议的内容.如果我将颜色属性设置为链接本身,文本颜色不会改变。

        让 linkAttributes: [NSAttributedString.Key : Any] = [ NSAttributedString.Key.foregroundColor: UIColor(named: "my_custom_green") ?? UIColor.blue ] textView.linkTextAttributes = 链接属性

      2. 我不希望 UITextView 滚动,我发现保持多行高度而不滚动的唯一方法(将 isScrollEnabled 设置为 false 对我不起作用)是将 scrollRangeToVisible 设置为我拥有的最后一个字符串范围.

        textView.scrollRangeToVisible(ppWithHyperlink.range)

      我不知道这是否是最好的选择,但这是我发现的……希望将来在 swiftUI 中有更好的方法来做到这一点!!!

      【讨论】:

        【解决方案5】:

        使用UITextView的可点击字符串

        struct TextLabelWithHyperlink: UIViewRepresentable {
        
        @State var tintColor: UIColor = UIColor.black
        @State var arrTapableString: [String] = []
        
        var configuration = { (view: UITextView) in }
        var openlink = {(strtext: String) in}
        
        func makeUIView(context: Context) -> UITextView {
            
            let textView = UITextView()
            textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
            textView.isEditable = false
            textView.isSelectable = true
            textView.tintColor = self.tintColor
            textView.delegate = context.coordinator
            textView.isScrollEnabled = false
            return textView
        }
        
        func updateUIView(_ uiView: UITextView, context: Context) {
            configuration(uiView)
            let stringarr  = NSMutableAttributedString(attributedString: uiView.attributedText)
            for strlink in arrTapableString{
                let link = strlink.replacingOccurrences(of: " ", with: "_")
                stringarr.addAttribute(.link, value: String(format: "https://%@", link), range: (stringarr.string as NSString).range(of: strlink))
            }
            uiView.attributedText = stringarr
        }
        
        func makeCoordinator() -> Coordinator {
            Coordinator(parent: self)
        }
        
        class Coordinator: NSObject,UITextViewDelegate {
            var parent : TextLabelWithHyperlink
            init(parent: TextLabelWithHyperlink) {
                self.parent = parent
            }
            
            func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
                let strPlain = URL.absoluteString.replacingOccurrences(of: "https://", with: "").replacingOccurrences(of: "_", with: " ")
                if (self.parent.arrTapableString.contains(strPlain)) {
                    self.parent.openlink(strPlain)
                }
                return false
            }
            
        }}
        

        swiftui中的实现

        TextLabelWithHyperlink(arrTapableString: ["Terms of Use", "Privacy Policy"]) { (textView) in
                                    let string = "Please contact us by filling contact form. We will contact with you shortly.  Your request will be processed in accordance with the Terms of Use and Privacy Policy."
                                    
                                    let attrib = NSMutableAttributedString(string: string, attributes: [.font: UIFont(name: Poodlife_Font.oxygen_regular, size: 14)!,.foregroundColor:  UIColor.black])
                                    
                                    attrib.addAttributes([.font: UIFont(name: Font.oxygen_bold, size: 14)!,
                                                          .foregroundColor:  UIColor.black], range: (string as NSString).range(of: "Terms of Use"))
                                    
                                    attrib.addAttributes([.font: UIFont(name: Font.oxygen_bold, size: 14)!,
                                                          .foregroundColor:  UIColor.black,
                                                          .link: "Privacy_Policy"], range: (string as NSString).range(of: "Privacy Policy"))
                                    
                                    textView.attributedText = attrib
                                } openlink: { (tappedString) in
                                    print("Tapped link:\(tappedString)")
                                }
        

        【讨论】:

          【解决方案6】:

          在 iOS 15 中你可以试试

          Text("Apple website: [click here](https://apple.com)")
          

          【讨论】:

            【解决方案7】:

            以下是我的完整 SwiftUI 解决方案。使用以下解决方案,您放入的任何容器都将被很好地格式化,并且您可以使您想要的特定文本可点击。

            struct TermsAndPrivacyText: View {
              @State private var sheet: TermsOrPrivacySheet? = nil
              let string = "By signing up, you agree to XXXX's Terms & Conditions and Privacy Policy"
              
              
              enum TermsOrPrivacySheet: Identifiable {
                case terms, privacy
                
                var id: Int {
                  hashValue
                }
              }
              
              
              func showSheet(_ string: String) {
                if ["Terms", "&", "Conditions"].contains(string) {
                  sheet = .terms
                }
                else if ["Privacy", "Policy"].contains(string) {
                  sheet = .privacy
                }
              }
              
              
              func fontWeight(_ string: String) -> Font.Weight {
                ["Terms", "&", "Conditions", "Privacy", "Policy"].contains(string) ? .medium : .light
              }
            
              
              private func createText(maxWidth: CGFloat) -> some View {
                var width = CGFloat.zero
                var height = CGFloat.zero
                let stringArray = string.components(separatedBy: " ")
                
                
                return
                  ZStack(alignment: .topLeading) {
                    ForEach(stringArray, id: \.self) { string in
                      Text(string + " ")
                        .font(Theme.Fonts.ofSize(14))
                        .fontWeight(fontWeight(string))
                        .onTapGesture { showSheet(string) }
                        .alignmentGuide(.leading, computeValue: { dimension in
                          if (abs(width - dimension.width) > maxWidth) {
                            width = 0
                            height -= dimension.height
                          }
                          
                          let result = width
                          if string == stringArray.last {
                            width = 0
                          }
                          else {
                            width -= dimension.width
                           }
                          
                          return result
                        })
                        .alignmentGuide(.top, computeValue: { dimension in
                          let result = height
                          if string == stringArray.last { height = 0 }
                          return result
                        })
                      }
                  }
                  .frame(maxWidth: .infinity, alignment: .topLeading)
                }
              
              
              var body: some View {
                  GeometryReader { geo in
                    ZStack {
                      createText(maxWidth: geo.size.width)
                    }
                  }
                  .frame(maxWidth: .infinity)
                  .sheet(item: $sheet) { item in
                    switch item {
                    case .terms:
                      TermsAndConditions()
                    case .privacy:
                      PrivacyPolicy()
                    }
                  }
              }
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2022-09-29
              • 2022-01-16
              • 2011-06-23
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多