NSAttributedString中行尾的NSKernAttributeName空格

ric*_*chy 9 nsattributedstring ios swift

使用NSKernAttributeName它时在每行的末尾放置一个空格,有什么方法可以解决这个问题吗?我可以将属性设置为:

NSRange(location: 0, length: self.text!.characters.count-1)
Run Code Online (Sandbox Code Playgroud)

但我不想为每一行设置这个.

这是我正在使用的游乐场的测试代码

//: Playground - noun: a place where people can play

import UIKit
import XCPlayground

var text = "Hello, playground\nhow are you?"

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.paragraphSpacing = 50
paragraphStyle.alignment = NSTextAlignment.Left
paragraphStyle.lineBreakMode = NSLineBreakMode.ByTruncatingTail

let attributes = [
    NSParagraphStyleAttributeName: paragraphStyle
    , NSKernAttributeName: 20
]


let attributedString = NSAttributedString(string: text, attributes: attributes)

let label = UILabel()
label.attributedText = attributedString
label.numberOfLines = 0
label.textColor = UIColor.greenColor()
label.backgroundColor = UIColor.orangeColor()
label.sizeToFit()
label.center = CGPoint(x: 500, y: 100)


var text2 = "What's up\nWhere are you?"
let attributedString2 = NSAttributedString(string: text2, attributes: attributes)

let label2 = UILabel()
label2.attributedText = attributedString2
label2.numberOfLines = 0
label2.textColor = UIColor.greenColor()
label2.backgroundColor = UIColor.orangeColor()
label2.sizeToFit()
label2.center = CGPoint(x: 500, y: 250)

var text3 = "Hello"
let attributedString3 = NSAttributedString(string: text3, attributes: attributes)

let label3 = UILabel()
label3.attributedText = attributedString3
label3.numberOfLines = 0
label3.textColor = UIColor.greenColor()
label3.backgroundColor = UIColor.orangeColor()
label3.sizeToFit()
label3.center = CGPoint(x: 500, y: 400)

let holderView = UIView(frame: CGRect(x: 0, y: 0, width: 1000, height: 500))
holderView.backgroundColor = UIColor.lightGrayColor()
holderView.addSubview(label)
holderView.addSubview(label2)
holderView.addSubview(label3)

XCPlaygroundPage.currentPage.liveView = holderView
Run Code Online (Sandbox Code Playgroud)

结果看起来像这样:

在行尾有字距调整的文本

您可以在每行的末尾看到空格.

Ale*_*ylo 2

这实际上是字距调整工作原理的定义;它调整字偶间距字符与下一个字符之间的间距。是否继续绘制下一个字符是无关紧要的。

\n\n

标准属性

\n\n
\n

kerning 属性指示后续字符应从当前字符\xe2\x80\x99s 字体定义的默认偏移量移动多少;正紧排表示进一步移动,负紧排表示更靠近当前字符。

\n
\n\n

如果有帮助,请考虑在文字处理器中执行此操作。如果启用了字距调整,并且您键入了一个字符,那么您希望插入点在哪里?预期的答案将是“从刚刚键入的字符偏移紧排量”,因为这就是紧排为 0 的默认情况下发生的情况,对吗?嗯,这正是这里发生的情况:如果您对字符串的最后一个字符进行紧排,则该字符串将包含最后一个紧排。

\n\n

因此,这里正确的做法是将 dropLast() 逻辑包装在扩展中,然后就到此为止了。

\n