在 TextView 中查找子字符串的 CGPoint 位置

Find CGPoint Location of substring in TextView

我想创建一个位于 UITextView 内子字符串位置的 SpriteKit 节点。我将如何检索 CGPoint 位置以便我可以将 SKNode 定位在那里?

    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

上使用 firstRectForRange(_:) 方法
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)