iOS-AttributedString富文本集合

本文用于记录工作中遇到富文本处理的方法

文本中穿插带link的链接,link部分自定义颜色(如图)

  • 将整句文本、需要添加链接的部分分别定义为常量
  • 计算出需要添加链接部分的Range
  • 设置颜色与链接
  • 配置整段文本
  • 用UITextView装在这段富文本
struct DisclaimerMaker {
      let text = "By clicking “Post”, I agree to The Knot’s Privacy Policy and Terms of Use"
      let policyLink = "your policy link"
      let termsOfUseLink = "terms of use link"
      let policyText = "Privacy Policy"
      let termsOfUseText = "Terms of Use"

      var attributedText: NSAttributedString {
          let paragraph = NSMutableParagraphStyle()
          paragraph.alignment = .center
          let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.subhead,
                                                           .foregroundColor: UIColor.textSubtle,
                                                           .paragraphStyle: paragraph]
          let attributedString = NSMutableAttributedString(string: text,
                                                           attributes: attributes)
          let policyRange = (text as NSString).range(of: policyText)
          let policyAttributes: [NSAttributedString.Key: Any] = [.link: policyLink,
                                                                 .font: UIFont.subhead]
          attributedString.setAttributes(policyAttributes,
                                         range: policyRange)
          let termsOfUseRange = (text as NSString).range(of: termsOfUseText)
          let termsOfUseAttributes: [NSAttributedString.Key: Any] = [.link: termsOfUseLink,
                                                                     .font: UIFont.subhead]
          attributedString.setAttributes(termsOfUseAttributes,
                                         range: termsOfUseRange)
          return attributedString
      }
  }

private(set) lazy var legalDisclaimerTextView: UITextView = {
      let textView = UITextView()
      textView.textContainerInset = .zero
      textView.isEditable = false
      textView.isScrollEnabled = false
      textView.textAlignment = .center
      textView.linkTextAttributes = [.foregroundColor: UIColor.linkOnLight,
                                     .underlineColor: UIColor.clear]
      textView.attributedText = DisclaimerMaker().attributedText
      return textView
  }()

文本中间穿插图片(如图)

  • Note:点击范围是整段文字,所以不需要将最后蓝色的部分单独写成UIButton,而且写成UIButton对于约束方面也很难写,所以可以考虑用富文本来处理


    iOS-AttributedString富文本集合_第1张图片
    • 定义一个NSTextAttachment,将它的image设置为最后向上的箭头以及设置颜色
    • 设置Close Image Credits的样式(这里也可以使用上面第一种计算Range的方法)
    • 配置整段富文本
    • 这里不需要点击,所以用UILabel装在富文本即可
        private static let creditsString: String = "Marni Rothschild Pictures, Lindsey Pantaleo Photography, Todd France Photography, Corbin Gurkin, Jocelyn Filley Photography, Thinkstock, Braedon Photography, Andrew Chan Photography, Jose Villa, Rhphotoarts, Laura Ivanova Photography, Abby Jiu Photography, Laura Ivanova Photography, KT Merry, Shutterstock, Sergio Kurhajec, Jen Fariello, Eric Kelley Photography, Jasmine Star, Dennis Lee Photography, Pen/Carlson, Carrie Patterson Photography, Jami Thompson Photography, Brian Dorsey Studios, Kate Headley Photography, Antonis Achilleos, Thinkstock, Devon Jarvis, Studio 222 Photography, Laura Ivanova Photography, Lens CAP Productions, Paper Antler, Beaux Arts Photographie, Anita Calero, Mel & Co., Samuel Lippke Studios, Look Wedding Photography, Alea Lovely, Justin & Mary Photography, Thinkstock, Shutterstock, Jess + Nate Studios, Braedon Photography, Joel Serrato"
        private func expandImageCreditsString() {
          let attributedString = NSMutableAttributedString(string: VendorCategoryImageCreditCollectionViewCell.creditsString)
          let iconView = NSTextAttachment()
          iconView.image = XOKitIcon.caretUp.image?.withTintColor(.iconLink, renderingMode: .alwaysTemplate)
          iconView.bounds = CGRect(x: 0, y: -4, width: 16, height: 16)
          let iconString = NSAttributedString(attachment: iconView)
          let closeString = NSMutableAttributedString(string: "  Close Image Credits",
                                                      attributes: [NSAttributedString.Key.foregroundColor: UIColor.iconLink,
                                                                   NSAttributedString.Key.font: UIFont.caption1])
          closeString.append(iconString)
          attributedString.append(closeString)
          creditTextLabel.attributedText = attributedString
      }
    

优化富文本固有代码

在日常项目中,富文本最主要就是设置行高等style,无论要设置什么其他样式,文本、字体都是必要的
所以可以扩展NSMutableAttributedString把固有的代码进行一次封装,使整体看起来更加简、美观

extension NSMutableAttributedString {
      class func initWithString(_ string: String,
                                    font: UIFont,
                                    foregroundColor: UIColor,
                                    minimumLineHeight: CGFloat,
                                    maximumLineHeight: CGFloat)
        -> NSMutableAttributedString {
            let style = NSMutableParagraphStyle()
            style.maximumLineHeight = maximumLineHeight
            style.minimumLineHeight = minimumLineHeight
            return initWithString(string,
                                  font: font,
                                  foregroundColor: foregroundColor,
                                  style: style)
    }
}

这个方法返回一个设置了字体、颜色、style的NSMutableAttributedString,将UILabel或UITextView的attributedText直接赋值就可以得到原有的效果
实际使用方法

groupNameLabel.attributedText = NSMutableAttributedString.initWithString(group.name.uppercased(),
                                                                                 font: .tb_font(larsseitMedium, andFontSize: 16),
                                                                                 foregroundColor: .tb_primaryCopy(),
                                                                                 minimumLineHeight: 24,
                                                                                 maximumLineHeight: 24)


未完待续
未经授权,请勿转载
谢谢!

你可能感兴趣的:(iOS-AttributedString富文本集合)