首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UITextInput.characterRange(at:)关闭了几个像素

UITextInput.characterRange(at:)关闭了几个像素
EN

Stack Overflow用户
提问于 2018-03-29 08:53:10
回答 1查看 274关注 0票数 0

在我的UITextView子类中添加了一个点击识别器之后,我试图获得正在被点击的字符:

代码语言:javascript
复制
var textRecognizer: UITapGestureRecognizer!
required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    textContainer.lineFragmentPadding = 0
    textContainerInset = .zero

    textRecognizer = UITapGestureRecognizer(target: self, action: #selector(textTapped))
    textRecognizer.numberOfTapsRequired = 1
    addGestureRecognizer(textRecognizer)
}

@objc func textTapped(recognizer: UITapGestureRecognizer) {
    let location = recognizer.location(in: self)
    if let cRange = characterRange(at: location) {
        let cPosition = offset(from: beginningOfDocument, to: cRange.start)
        let cChar = text[Range(NSRange(location: cPosition, length: 1), in: text)!]
        print(cChar)
    }
}

问题是,如果我的attributedText是"Hello world\nWelcome to Stack Overflow",并且我点击字母的左边,就像字母f的左边,那么characterRange(at: location)返回前一个字母r,而不是返回f

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-29 11:08:18

在我看来,characterRange(at:)是有缺陷的:

  • 如果在索引n处给它在字符左侧的一个点,它将返回范围(n-1, n)
  • 如果在索引n处给它在字符右半部分的一个点,它将返回范围(n, n+1)
  • 如果在索引beginningOfDocument处给出字符左侧的一个点,则返回nil
  • 如果在索引endOfDocument处在字符的右半部分给出一个点,则返回(endOfDocument, endOfDocument+1)

textInput末端行为的差异证明了在某个地方有一个错误。

它的行为类似于一种“点上的光标位置”函数,这使得判断哪个字符在这一点上是不可靠的:是光标之前的字符还是光标后面的字符?

closestPosition(to:)也面临着同样的问题。

一个可行的替代方案是layoutManager.characterIndex(for:in:fractionOfDistanceBetweenInsertionPoints:)Credit to vacawama

代码语言:javascript
复制
@objc func textTapped(recognizer: UITapGestureRecognizer) {
    var location = recognizer.location(in: self)
    location.x -= textContainerInset.left
    location.y -= textContainerInset.top
    let cPosition = layoutManager.characterIndex(for: location, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
    let cChar = text[Range(NSRange(location: cPosition, length: 1), in: text)!]
    print(cChar)
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49551760

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档