0

I have a goal to implement local search inside Core Data entities. Technical part of finding occurrences is pretty clear. But I'm not sure how to display it correctly. Case: we have string in our entity

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor

and user want to find entries with word adipiscing. We have UILabel with width i.e. 320dp and numberOfLines = 1. If we will display whole string without correct trimming it would be

Lorem ipsum dolor sit amet, consec...

which just useless for user. I want label to look like

...consectetur adipiscing elit, se...

So in other words I want search occurrence to be "focused" somewhere about middle of UILabel. How can I trim the string where occurrence has happened depending on label font and width?

KY1VSTAR
  • 395
  • 4
  • 16

2 Answers2

0

It's not complete, but should bring you on track:

let wholeString = "This is a very long Hello world in a simple String"
let someSearch = wholeString.range(of: "Hello")!

// Make sure to call dropLast() twice to remove the space before 'Hello'
var stringBeforeSomeSearch = wholeString[wholeString.startIndex...someSearch.lowerBound].dropLast().dropLast()

// This is everything before the searched string
let prefixRange = stringBeforeSomeSearch.range(of: " ", options: .backwards)!.upperBound...someSearch.lowerBound

print(wholeString[prefixRange]) // prints "long H"
print(wholeString[prefixRange.lowerBound...someSearch.upperBound]) // prints "long Hello "

If you need more explanation, I'll be back later on.

RedX
  • 461
  • 1
  • 4
  • 14
0

Here's a solution that uses UITextView instead of UILabel, to achieve the desired search visualisation.

The concept is to use a UITextView with userInteraction and vertical scroll disabled and horizontal scroll enabled. Use the textView method of scroll to range to show the desired word.

let textView = UITextView()
textView.isUserInteractionEnabled = false
textView.contentSize = CGSize(width: textWidth, height: textView.frame.size.width)
scrollTo(text: "swift")


func scrollTo(text: String) {
    if let string = textView.text,
        let range = string.localizedStandardRange(of: text) {
        let viewRange = NSRange(range, in: string)
        textView.scrollRangeToVisible(viewRange)
    }
}

textWidth is the width of your total text. Follow this link for help.

udbhateja
  • 948
  • 6
  • 21