Swift中如何为Attributed String设置前两行自定义间距、第三行保持段落样式
你需要为AttributedString的不同文本范围设置不同的段落样式即可实现需求,具体实现如下:
适配硬换行场景(你的现有代码场景,文本带\n分隔每行)
let myString = "Your account phone numbers are listed here.\nTo change or delete a phone number, tap on it.\nTo add a phone number, go to the top right-hand corner of your screen and tap on “Add”." let font = UIFont.systemFont(ofSize: 14) let attributedString = NSMutableAttributedString(string: myString, attributes: [.font: font]) // 定义两种段落样式 let spacedParagraphStyle = NSMutableParagraphStyle() spacedParagraphStyle.lineSpacing = 8 // 可根据设计要求调整行间距数值 spacedParagraphStyle.lineBreakMode = .byWordWrapping let normalParagraphStyle = NSMutableParagraphStyle() normalParagraphStyle.lineBreakMode = .byWordWrapping // 拆分文本获取每行对应的范围 let lineParts = myString.components(separatedBy: .newlines) guard lineParts.count >= 3 else { displayLabel.attributedText = attributedString return } let firstLineRange = NSRange(location: 0, length: lineParts[0].count + 1) // +1计入换行符 let secondLineRange = NSRange(location: firstLineRange.upperBound, length: lineParts[1].count + 1) let thirdLineRange = NSRange(location: secondLineRange.upperBound, length: lineParts[2].count) // 给对应范围设置段落属性 attributedString.addAttribute(.paragraphStyle, value: spacedParagraphStyle, range: firstLineRange) attributedString.addAttribute(.paragraphStyle, value: spacedParagraphStyle, range: secondLineRange) attributedString.addAttribute(.paragraphStyle, value: normalParagraphStyle, range: thirdLineRange) displayLabel.attributedText = attributedString
适配自动折行场景(无硬换行符,依赖Label宽度自动换行)
如果你的文本没有手动插入\n,需要先通过文本布局计算每行对应的范围,再设置属性:
// 接上文创建的attributedString displayLabel.sizeToFit() let labelWidth = displayLabel.bounds.width // 构建文本布局计算行范围 let textStorage = NSTextStorage(attributedString: attributedString) let layoutManager = NSLayoutManager() textStorage.addLayoutManager(layoutManager) let textContainer = NSTextContainer(size: CGSize(width: labelWidth, height: .greatestFiniteMagnitude)) textContainer.lineFragmentPadding = 0 textContainer.maximumNumberOfLines = 0 layoutManager.addTextContainer(textContainer) var lineRanges: [NSRange] = [] var currentIndex = 0 while currentIndex < myString.utf16.count { let lineRange = layoutManager.lineFragmentRange(forGlyphAt: currentIndex, effectiveRange: nil) lineRanges.append(lineRange) currentIndex = NSMaxRange(lineRange) } // 给前两行设置行间距,剩余行用默认样式 if lineRanges.count >= 2 { attributedString.addAttribute(.paragraphStyle, value: spacedParagraphStyle, range: lineRanges[0]) attributedString.addAttribute(.paragraphStyle, value: spacedParagraphStyle, range: lineRanges[1]) } if lineRanges.count >= 3 { for i in 2..<lineRanges.count { attributedString.addAttribute(.paragraphStyle, value: normalParagraphStyle, range: lineRanges[i]) } } displayLabel.attributedText = attributedString
内容的提问来源于stack exchange,提问作者iOSDuDe
相关产品推荐
相关产品推荐

