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.