創(chuàng)建
String
擴(kuò)展
源碼
// MARK: - 字符串處理
extension String {
func getParagraphStringHeight(lineHeight: CGFloat, font: UIFont, maxWidth: CGFloat) -> CGFloat {
let paraStyle = NSMutableParagraphStyle()
paraStyle.maximumLineHeight = lineHeight
paraStyle.minimumLineHeight = lineHeight
let attri = [NSAttributedString.Key.font: font,
NSAttributedString.Key.paragraphStyle: paraStyle]
let size = (self as NSString).boundingRect(with: CGSize(width: maxWidth, height: CGFloat(MAXFLOAT)),
options: [.usesLineFragmentOrigin, .usesFontLeading],
attributes: attri,
context: nil).size
let textHeight = CGFloat(ceilf(Float(size.height)))
return textHeight < lineHeight ? lineHeight : textHeight
}
func getAttributedText(_ font: UIFont, color: UIColor, lineHeight: CGFloat) -> NSAttributedString {
let paraStyle = NSMutableParagraphStyle()
paraStyle.minimumLineHeight = lineHeight
paraStyle.maximumLineHeight = lineHeight
let attrs = [NSAttributedString.Key.font: font,
NSAttributedString.Key.foregroundColor: color,
NSAttributedString.Key.paragraphStyle: paraStyle]
return NSAttributedString.init(string: self, attributes: attrs)
}
func getStringWidth(width: CGFloat, height: CGFloat, font: UIFont) -> CGFloat {
let size = (self as NSString).boundingRect(with: CGSize(width: width, height: height),
options: [.usesLineFragmentOrigin, .usesFontLeading],
attributes: [NSAttributedString.Key.font: font],
context: nil).size
let textWidth = CGFloat(ceilf(Float(size.width)))
return textWidth
}
func getAttributedString(subStrings: [String], colors: [UIColor], fonts: [UIFont]) -> NSAttributedString {
let paraStyle = NSMutableParagraphStyle()
paraStyle.lineBreakMode = .byCharWrapping
let attributedString = NSMutableAttributedString.init(string: self,
attributes: [NSAttributedString.Key.paragraphStyle: paraStyle,
NSAttributedString.Key.kern: 0.0])
if subStrings.count != colors.count, subStrings.count != fonts.count {
return attributedString
}
for (index, _) in subStrings.enumerated() {
/// 子字符串
let string = subStrings[index]
let range = NSString(string: self).range(of: string)
/// 顏色
let color = colors[index]
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
/// 字體大小
let font = fonts[index]
attributedString.addAttribute(NSAttributedString.Key.font, value: font, range: range)
}
return attributedString
}
}
針對改變字符串字體樣式再計算高度方式仇味,限制最大寬度
let size = contentLabel.sizeThatFits(CGSize(width: contentWidth, height: CGFloat(MAXFLOAT)))