美文网首页
iOS 获取字符在TextView中的位置

iOS 获取字符在TextView中的位置

作者: 一天天的啊哈哈 | 来源:发表于2023-03-27 15:15 被阅读0次

使用NSLayoutManager的这个API,传入字符在整个文本的NSRange,和当前TextView的textContainer。
open func boundingRect(forGlyphRange glyphRange: NSRange, in container: NSTextContainer) -> NSRect

简单示例

let str = "123321123"
let ranges = getPatternRangeArr(pattern: "123", content: str)

for i in 0..<ranges.count {
   let r = ranges[i]
   let rect = textView.layoutManager.boundingRect(forGlyphRange: r, in: textView.textContainer)
}

获取字符NSRange的方法

func getPatternRangeArr(pattern: String,content: String) -> [NSRange] {
    var ranges:[NSRange] = []
    do {
        let regular = try NSRegularExpression(pattern: pattern,options: .caseInsensitive)
        let results = regular.matches(in: content,options: .reportProgress, range: NSRange(location: 0, length: content.count))
        for r in results {
            ranges.append(r.range)
        }
    } catch {
        print(error)
    }
        
    return ranges
}

相关文章

  • Android TextView获取某个字符的坐标

    在TextView是通过Layout来管理字符的位置 注意获取到的这个坐标是TextView的相对坐标。 我们可以...

  • 获取某个字符在TextView中的位置(坐标)

    一、普通TextView 获取某个字符相对于TextView的坐标 二、获取ClickSpan 点击的坐标

  • JavaScript 中 String 的方法

    获取String中字符的三种方式 charAt(position)获取字符串中position位置的字符,索引从0...

  • iOS获取当前视图在屏幕中的位置

    iOS获取当前视图在屏幕中的位置 UIWindow * window=[[[UIApplication share...

  • UITextView inputDelegate

    背景:在 textView 末尾插入字符串分析:不知前面是否已经有 字符,插入的位置,如何处理? 解决:

  • Day3 字符串和字符串相关运算

    一、获取字符 1、获取单个字符 字符串中的每一个字符都会对应一个唯一的下标(索引)用来表示字符在字符串中的位置。 ...

  • day04 字符串

    获取字符 1.获取单个字符 字符串中的每一个字符都会对应一个唯一的下标(索引)用来表示字符在字符串中的位置。 下标...

  • 2018-05-08 实现String.xml中添加多个空格

    场景: 在TextView中显示String的字符串,需要显示多个空格问题: 在TextView中显示Shtrin...

  • day-04 字符串

    获取字符 1.获取单个字符 字符串中没一个字符都会对应一个下标(索引),用来表示字符在字符串中的位置下标是从0开始...

  • String

    1、获取1.1 字符串中的包含的字符数,也就是字符串的长度。int length(): 获取长度。1.2 根据位置...

网友评论

      本文标题:iOS 获取字符在TextView中的位置

      本文链接:https://www.haomeiwen.com/subject/prdzrdtx.html