I have a UiTextView I use to display detail text. Sometimes the text can be lengthy enough to scroll through it. Sometimes the text can be short enough that it fits within the frame of the UITextView.
I also implement a search feature that one can use to search longer text strings. The function adds a font color attribute to the text matching the search input string. The function collects an array of NSRange values for each matched search string input. I am using regex to match the search string and return the array of NSRange values for each match.
I am presently developing a function that animates the user to the UITextView position of the matched search string.
I will later provide a button the user can click to cycle through the matches.
So far, everything works very well. See code below. detailText is the UITextView:
// rangeOfSearchText uses a regex to return the range of the match. For text purposes, the function returns the first index only.
let rangeOfMatch = rangeOfSearchText(searchString: self.searchText!, UIText: self.detailText.text)
let glyRange = self.detailText.layoutManager.glyphRange(forCharacterRange: rangeOfMatch, actualCharacterRange:nil)
let rect = self.detailText.layoutManager.lineFragmentRect(forGlyphAt: NSMaxRange(glyRange), effectiveRange: nil)
self.detailText.scrollRectToVisible(rect, animated: true)
While the code works well, the matched text shows up at the bottom of the resulting UITextView frame. I want the matched text to appear in the middle of the view. I tried the following bit of code which kinda works:
self.detailText.contentOffset.y = 200
contentOffset works as intended only if the matched text range is in the middle of a larger multiline string. If the matched text range is at the beginning of the string, implementing contentOffset scrolls the user past the matched text by 200. Basically, the matched text scrolls out of view. That is no good. If the matched text is at the end of the multiline text, contentOffset adds more whitespace to position the matched text in the middle of the view. Neither result is desired. I can live with the latter, but the former is no good because it scrolls the first matched text up out of view.
I've searched for a similar issue on stack overflow but cannot find it. If it does exist, kindly point it out. If not, any suggestion is welcome.
This appears to work:
}