![](/img/trans.png)
[英]NSLayoutManager, boundingRectForGlyphRange and emoji
[英]NSLayoutManager boundingRectForGlyphRange off by some Points
我想“突出”UITextView中的特定單詞,而不是純色(可以通過NSAttributedString
),而是使用漸變和其他一些奇特的效果。
因此,我決定有必要使用給定文本的邊界矩形手動創建視圖並覆蓋(或底層)它。
令我驚訝的是,事實證明這非常簡單。 示例在UIViewController中, txtView
是作為IBOutlet
連接的UITextView
:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Converting to NSString as I need a NSRange for glphyRangeForCharacterRange
// (a normal String in Swift returns a Range)
let charRange = (txtView.text as NSString).rangeOfString("dolor sit er elit")
assert(charRange.location != NSNotFound, "Character Range could not be found.")
let glyphRange = txtView.layoutManager.glyphRangeForCharacterRange(charRange,
actualCharacterRange: nil)
let glyphContainer = txtView.layoutManager.textContainerForGlyphAtIndex(glyphRange.location, effectiveRange: nil)
let glyphRect = txtView.layoutManager.boundingRectForGlyphRange(glyphRange,
inTextContainer: glyphContainer!)
let highlightView = UIView(frame: glyphRect)
highlightView.alpha = 0.3
highlightView.backgroundColor = UIColor.redColor()
txtView.addSubview(highlightView)
}
可悲的是,這導致了覆蓋的視圖(在下面的屏幕截圖中為紅色),被幾個點關閉。
它似乎總是相同數量。 這意味着我可能會硬編碼,但這從來都不是一個好主意。 在Simulator中使用各種設備和帶有iOS 8.1.3的iPhone 6進行了測試。
我還嘗試了其他變體(通過創建我自己的NSTextContainer等),受到關於如何獲得子串的CGRect的問題的啟發,並且“boundingRectForGlyphRange並不總是適用於所有字符串”
任何想法(除了訴諸CoreText )?
嘗試通過textview的textContainerInset調整字形rect:
var glyphRect = txtView.layoutManager.boundingRectForGlyphRange(glyphRange,
inTextContainer: glyphContainer!)
glyphRect.origin.y += txtView.textContainerInset.top
這應該夠了吧!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.