chi*_*uda 5 core-text ios swift
我正在尝试将 aUILabel中的每一行添加到数组中,但我使用的代码似乎并不十分准确。
func getLinesArrayOfStringInLabel(label:UILabel) -> [String] {
guard let text: NSString = label.text as? NSString else { return [] }
let font:UIFont = label.font
let rect:CGRect = label.frame
let myFont: CTFont = CTFontCreateWithName(font.fontName as CFString, font.pointSize, nil)
let attStr:NSMutableAttributedString = NSMutableAttributedString(string: text as String)
attStr.addAttribute(NSAttributedStringKey.font, value:myFont, range: NSMakeRange(0, attStr.length))
let frameSetter:CTFramesetter = CTFramesetterCreateWithAttributedString(attStr as CFAttributedString)
let path: CGMutablePath = CGMutablePath()
path.addRect(CGRect(x: 0, y: 0, width: rect.size.width, height: 100000))
let frame:CTFrame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil)
let lines = CTFrameGetLines(frame) as NSArray
var linesArray = [String]()
for line in lines {
let lineRange = CTLineGetStringRange(line as! CTLine)
let range:NSRange = NSMakeRange(lineRange.location, lineRange.length)
let lineString = text.substring(with: range)
linesArray.append(lineString as String)
}
return linesArray
}
let label = UILabel()
label.numberOfLines = 0
label.frame = CGRect(x: 40, y: 237, width: 265, height: 53)
label.font = UIFont.systemFont(ofSize: 22, weight: UIFont.Weight.regular)
label.text = "Hey there how's it going today?"
label.backgroundColor = .red
bg.addSubview(label)
print(getLinesArrayOfStringInLabel(label: label))
Run Code Online (Sandbox Code Playgroud)
这打印
["Hey there how\'s it going ", "today?"]
Run Code Online (Sandbox Code Playgroud)
但是标签看起来像这样:
我希望得到["Hey there how\'s it ", "going today?"]. 这是怎么回事?
因此,这似乎是UILabel您正在使用的功能的问题,而不是问题。我怀疑 aCATextLayer会渲染这些行如何从该方法返回,我悲伤地发现:(我是对的。
红色是您用来创建UILabel.
绿色具有CATextLayer与上面所有相同的特征,UILabel包括字体、字体大小和框架大小。
黄色是一个子类UIView,它正在替换自己的图层并返回CATextLayer. 我把它附在下面。您可以继续构建它来满足您的需求,但我认为这是真正的解决方案,也是唯一一个将获取行与用户看到的可见行相匹配的解决方案。如果您想出更好的解决方案,请告诉我。
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
您还应该查看GitHub 上的Core-Text-Label。CATextLayers它的渲染与 get 行的返回完全一致。它无法满足我的特殊需求,因为我需要调整大小并且它崩溃了,但如果不需要调整大小,那么我会检查一下。
最后我又回来了,看来这可能是 iOS 11 中开始出现的自动换行问题,他们不会在一行中留下孤立的单词。
| 归档时间: |
|
| 查看次数: |
2491 次 |
| 最近记录: |