gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 22:28:45 24 4
gpt4 key购买 nike

我想创建一个位于 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)

关于ios - 在 TextView 中查找子字符串的 CGPoint 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28468187/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com