Search code examples
iosswiftsprite-kituitextviewnsattributedstring

Find CGPoint Location of substring in TextView


I'm looking to create a SpriteKit Node positioned at the location of a substring inside a UITextView. How would I retrieve the CGPoint location so I can position the SKNode there?

    let textFont = [NSFontAttributeName: UIFont(name: "GillSansMT", size: 30.0) ?? UIFont.systemFontOfSize(18.0)]
    attrString1 = NSMutableAttributedString(string: "My name is Dug.", attributes: textFont)
    textShown1 = CustomTextView(frame: CGRectMake(CGRectGetMidX(self.frame), 175 + (90 * paragraphNumber), CGRectGetWidth(self.frame) - 80, CGRectGetHeight(self.frame)-400))
    textShown1.attributedText = attrString1

    self.view?.addSubview(textShown1)

Solution

  • You can use firstRectForRange(_:) method on UITextView

    let textFont = [NSFontAttributeName: UIFont(name: "GillSansMT", size: 30.0) ?? UIFont.systemFontOfSize(18.0)]
    let attrString1 = NSMutableAttributedString(string: "My name is Dug.", attributes: textFont)
    
    // range of substring to search
    let str1 = attrString1.string as NSString
    let range = str1.rangeOfString("name", options: nil, range: NSMakeRange(0, str1.length))
    
    // prepare the textview
    let textView = UITextView(frame:CGRectMake(0,0,200,200))
    textView.attributedText = attrString1
    
    // you should ensure layout
    textView.layoutManager.ensureLayoutForTextContainer(textView.textContainer)
    
    // text position of the range.location
    let start = textView.positionFromPosition(textView.beginningOfDocument, offset: range.location)!
    // text position of the end of the range    
    let end = textView.positionFromPosition(start, offset: range.length)!
    
    // text range of the range
    let tRange = textView.textRangeFromPosition(start, toPosition: end)
    
    // here it is!
    let rect = textView.firstRectForRange(tRange)