这个问题与a problem I had yesterday有关,我应该可以针对此问题创建解决方法。当我进一步调查时,我发现它的发生范围比我最初想象的要广泛。我以前只在显示的文本中至少包含一个换行符来注意到它,但是下面的情况并非如此。
问题似乎是由于使用NSLayoutManager的boundingRect方法获取(除其他事项外)单个字符宽度,然后使用这些宽度设置字符的UITextView框架宽度属性导致的。这样做显然会导致将文本视图的backgroundColor设置为UIColor.clear的设置被忽略(即背景变得不透明)。下面的Playground代码再现了问题,以红色文本显示,并以黑色显示了使用宽度常量的解决方法。字距调整得越紧,效果越明显。
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
let view = UIView()
view.bounds = CGRect(x: -100, y: -100, width: 200, height: 200)
view.backgroundColor = .white
let str = "..T.V.W.Y.."
let strStorage = NSTextStorage(string: str)
let layoutManager = NSLayoutManager()
strStorage.addLayoutManager(layoutManager)
let textContainer = NSTextContainer(size: view.bounds.size)
textContainer.lineFragmentPadding = 0.0
layoutManager.addTextContainer(textContainer)
let strArray = Array(str)
struct CharInfo {
var char: Character
var origin: CGPoint?
var size: CGSize?
}
var charInfoArray = [CharInfo]()
for index in 0..<str.count {
charInfoArray.append(CharInfo.init(char: strArray[index], origin: nil, size: nil))
let charRange = NSMakeRange(index, 1)
let charRect = layoutManager.boundingRect(forGlyphRange: charRange, in: textContainer)
charInfoArray[index].origin = charRect.origin
charInfoArray[index].size = charRect.size
}
for charInfo in charInfoArray {
let textView0 = UITextView()
textView0.backgroundColor = UIColor.clear // Ignored in this case!!
textView0.text = String(charInfo.char)
textView0.textContainerInset = UIEdgeInsets.zero
let size0 = charInfo.size!
textView0.frame = CGRect(origin: charInfo.origin!, size: size0)
textView0.textContainer.lineFragmentPadding = CGFloat(0.0)
textView0.textColor = UIColor.red
view.addSubview(textView0)
let textView1 = UITextView()
textView1.backgroundColor = UIColor.clear // Required
textView1.text = String(charInfo.char)
textView1.textContainerInset = UIEdgeInsets.zero
var size1 = charInfo.size!
size1.width = 20 // But changing .height has no effect on opacity
textView1.frame = CGRect(origin: charInfo.origin!, size: size1)
textView1.frame = textView1.frame.offsetBy(dx: 0, dy: 20)
textView1.textContainer.lineFragmentPadding = CGFloat(0.0)
textView1.textColor = UIColor.black
view.addSubview(textView1)
}
self.view = view
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
答案 0 :(得分:0)
这似乎是一个错误,但与NSLayoutManager的实例方法boundingRect(forGlyphRange:in :)一起使用。它只是看起来,就像它可能是透明度更改一样。
根据Apple's documentation,boundingRect(forGlyphRange:in :)应该“(返回)一个单独的边界矩形(在容器坐标中),该矩形将所有字形和在给定字形中绘制在给定文本容器中的其他标记括起来范围,包括在其线段矩形之外绘制的字形和诸如下划线的文本属性。”但这不是它的作用。
在这种情况下,由于字距调整,每个boundingRect的宽度减少了下一个字形向左移动的量。例如,您可以使用str =“ ToT”并在设置后立即添加print(size0.width)进行测试。您会得到的:
6.0 // "T"; should have been 7.330078125
6.673828125 // "o"
7.330078125 // "T"
在此错误修复之前,一种解决方法是单独计算每个字符的字形大小。