gpt4 book ai didi

ios - NSAttributedString 行尾的 NSKernAttributeName 空格

转载 作者:IT王子 更新时间:2023-10-29 05:44:46 27 4
gpt4 key购买 nike

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

NSRange(location: 0, length: self.text!.characters.count-1)

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

这是我正在使用的 Playground 中的测试代码

//: 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

结果是这样的:

text with kerning at the end of a line

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

最佳答案

这实际上是字距调整工作原理的定义;它调整紧缩字符和下一个字符所在位置之间的空间。是否继续绘制下一个字符无关紧要。

Standard Attributes

The kerning attribute indicates how much the following character should be shifted from its default offset as defined by the current character’s font; a positive kern indicates a shift farther along and a negative kern indicates a shift closer to the current character.

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

所以这里正确的做法是将您的 dropLast() 逻辑包装在一个扩展中,然后收工。

关于ios - NSAttributedString 行尾的 NSKernAttributeName 空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37594704/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com