在TextView中找到子字符串的CGPoint位置 [英] Find CGPoint Location of substring in TextView

查看:92
本文介绍了在TextView中找到子字符串的CGPoint位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找创建一个SpriteKit节点,该节点位于UITextView内子字符串的位置.我将如何检索CGPoint位置,以便将SKNode定位在该位置?

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)

推荐答案

您可以在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)

这篇关于在TextView中找到子字符串的CGPoint位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆