美文网首页
Swift文字相关的处理方法

Swift文字相关的处理方法

作者: 奋斗的遗忘人 | 来源:发表于2022-09-28 09:29 被阅读0次

    1.计算加粗文本的宽度

    /// 加粗文字的宽度
        /// - Parameters:
        ///   - text: 文本
        ///   - fontSize: 字体大小
        ///   - height: 高度
        /// - Returns:高度
        public static func textBoldWidth(text: String, fontSize: CGFloat, height: CGFloat) -> CGFloat {  
           return text.boundingRect(with:CGSize(width:CGFloat(MAXFLOAT), height: height), options: .usesLineFragmentOrigin, attributes: [.font:UIFont.boldSystemFont(ofSize: fontSize)], context:nil).size.width
        }
    
    1. 文字的高度
     /// 文字的高度
        /// - Parameters:
        ///   - text: 文本
        ///   - fontSize: 字体大小
        ///   - width: 宽度
        /// - Returns:高度
        public static func textHeight(text: String, fontSize: CGFloat, width: CGFloat) -> CGFloat { 
              return text.boundingRect(with:CGSize(width:width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [.font:UIFont.systemFont(ofSize: fontSize)], context:nil).size.height
        }
    

    3.指定文字加粗或改变其属性的方法

    /// 富文本改变指定文字的属性
        /// - Parameters:
        ///   - style: 正常文本属性
        ///   - highlightedText: 指定的文字
        ///   - highlightedTextStyle: 指定文字的属性
        /// - Returns: 返回富文本
        func attributedString(with style: [NSAttributedString.Key: Any]? = nil, and highlightedText: String, with highlightedTextStyle: [NSAttributedString.Key: Any]? = nil) -> NSAttributedString {
            let formattedString = NSMutableAttributedString(string: self, attributes: style)
            let highlightedTextRange: NSRange = (self as NSString).range(of: highlightedText as String)
            formattedString.setAttributes(highlightedTextStyle, range: highlightedTextRange)
            return formattedString
        }
    

    调用方法:

     /// 特定文字加粗
      let attributedText = routeText.attributedString(with: [.font:UIFont.systemFont(ofSize: 16, weight: .regular), .foregroundColor:.black], and: totalDistance, with: [.font:UIFont.systemFont(ofSize: 20, weight: .bold), .foregroundColor:.black])
    

    相关文章

      网友评论

          本文标题:Swift文字相关的处理方法

          本文链接:https://www.haomeiwen.com/subject/khohartx.html