Getting CGRect for text in a UITextView for the purpose of highlighting with a CALayer

为君一笑 提交于 2019-12-03 20:06:26

To position the layer correctly, you only have to add self.textView.textContainerInset.top to textRect.origin.y, not the text view's origin.

But as I said in the comment, it won't work nicely if your match is across two lines. You may want to set the background colour of the matched range to highlight it, (using the attributedText property), but then you can't add the rounded corners or shadow.

[textView textContainerInset]

Using the origin of the text view will not work because the insets may be changed somewhere else. An example would be if the parent view controller’s automaticallyAdjustsScrollViewInsets property is YES, or some custom text container layout is going on.

UIEdgeInsets textContainerInset = [[self textView]textContainerInset];
textRect.origin.x += textContainerInset.left;
textRect.origin.y += textContainerInset.top;

This is a solution for getting the geometry correct, but not if the text spans two lines.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!