Find CGPoint Location of substring in TextView

Chris

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)
rintaro

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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

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

来自分类Dev

CGPoint快速或CGPoint

来自分类Dev

Index and length must refer to a location within the string error in substring

来自分类Dev

android-location 显示在 toast 中,但不在 textview 中

来自分类Dev

错误权限 ACCESS_FIND_LOCATION

来自分类Dev

当substring只是换行符时,string.find(substring)函数返回什么?

来自分类Dev

Swift CGPoint异常行为

来自分类Dev

Create random CGPoint with Swift

来自分类Dev

Swift CGPoint unusual behaviour

来自分类Dev

AnyObject到CGPoint

来自分类Dev

CGPoint标量乘法Swift

来自分类Dev

'(Int,Int)'与'CGPoint'不同

来自分类Dev

CGPoint标量乘法Swift

来自分类Dev

AnyObject到CGPoint

来自分类Dev

在CGPoint上绘制文本

来自分类Dev

围绕另一个CGPoint旋转CGPoint

来自分类Dev

CGPoint上的CGAffineTransformMakeRotation意外值

来自分类Dev

从扩展名返回CGPoint

来自分类Dev

如何快速比较CGPoint?

来自分类Dev

使用Swift创建随机CGPoint

来自分类Dev

Swift-SpriteKit CGPoint对齐

来自分类Dev

Swift的POPSpringAnimation toValue CGPoint错误

来自分类Dev

如何创建多维CGPoint数组?

来自分类Dev

将NSValue转换回CGPoint

来自分类Dev

如何快速比较CGPoint?

来自分类Dev

Swift-SpriteKit CGPoint对齐

来自分类Dev

SpriteKit:在CGPoint上获取节点

来自分类Dev

Regex pattern to find n non-space characters of x length after a certain substring

来自分类Dev

Swift数字和CGFloat(CGPoint,CGRect等)