更新时间:2023-02-05 10:47:16
所以看起来它与UILabel有关,而且你使用的功能没有问题。我怀疑CATextLayer会渲染它们是如何从该方法返回的,我发现这很遗憾:(我是对的。
So it appears to be something with UILabel and not something wrong with the function you are using. It was my suspicion that a CATextLayer would render the lines how they are returned from that method and I found out sadly :( that I am right.
这是一张照片我的结果:
Here is a picture of my results:
红色是您用来创建UILabel的确切代码。
The red is the exact code you used to create your UILabel.
绿色是CATextLayer,具有上述UILabel的所有相同特征,包括字体,字体大小和帧大小。
The green is a CATextLayer with all of the same characteristics of the UILabel from above including font,fontsize, and frame size.
黄色是一个子类UIView,它正在替换它自己的层并返回一个CATextLayer。我在下面附上它。你可以继续构建它以满足你的需求但我认为这是真正的解决方案,也是唯一一个让得到的线条与用户看到的可见线条相匹配。如果你想出更好的解决方案,请告诉我。
The yellow is a subclassed UIView that is replacing its own layer and returning a CATextLayer. I am attaching it below. You can continue to build it out to meet your needs but I think this is the real solution and the only one that will have the get lines matching the visible lines the user sees. If you come up with a better solution please let me know.
import UIKit
class AGLabel: UIView {
var alignment : String = kCAAlignmentLeft{
didSet{
configureText()
}
}
var font : UIFont = UIFont.systemFont(ofSize: 16){
didSet{
configureText()
}
}
var fontSize : CGFloat = 16.0{
didSet{
configureText()
}
}
var textColor : UIColor = UIColor.black{
didSet{
configureText()
}
}
var text : String = ""{
didSet{
configureText()
}
}
override class var layerClass: AnyClass {
get {
return CATextLayer.self
}
}
func configureText(){
if let textLayer = self.layer as? CATextLayer{
textLayer.foregroundColor = textColor.cgColor
textLayer.font = font
textLayer.fontSize = fontSize
textLayer.string = text
textLayer.contentsScale = UIScreen.main.scale
textLayer.contentsGravity = kCAGravityCenter
textLayer.isWrapped = true
}
}
}
您还应该查看核心 - GitHub上的文本标签。它完全像CATextLayers那样呈现,并且与get行的返回相匹配。它不适用于我的特殊需求,因为我需要我的可调整大小并且崩溃但是如果不需要调整大小那么我会检查它。
You should also check out Core-Text-Label on GitHub. It renders exactly as the CATextLayers do and would match the return of the get lines. It won't work for my particular needs as I need mine to be resizable and it crashes but if resizing is not need then I would check it out.
最后我是再回来看来,这可能是在iOS 11中开始的自动换行问题,他们不会在一行上留下孤儿字。
Finally I am back again and it appears that it could be a problem of word wrap that was started in iOS 11 where they do not leave an orphan word on a line.