找到uilabel中文本的位置{x,y} [英] find the location {x,y} of text in uilabel

查看:68
本文介绍了找到uilabel中文本的位置{x,y}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自服务器的字符串,我在UILabel multiligne上显示。它在该字符串中,我正在识别一些特定的子字符串。我想在子字符串上放置一个按钮(按钮将是UILabel的子视图)。为此,我需要子串坐标。我经历过这个,但我无法理解。假设我的完整字符串是abc,567-324-6554,纽约。我希望567-324-6554显示在我需要其坐标的按钮上。
如何使用上面的链接查找子串的坐标?
谢谢,

I have a string coming from server which I am displaying on UILabel multiligne. It is within that string, I am identifying some particular substring. I want to place a button on that substring(button will be a subview of UILabel). For this I require substring coordinates. I went through this but I am not able to understand it. Suppose my complete string is abc, 567-324-6554, New York. I want 567-324-6554 to be displayed on button for which I need its coordinates. How can I use above link to find coordinates of substring? Thanks,

推荐答案

UILabel 没有这样做的方法。您可以使用 UITextView ,因为它实现了 UITextInput protocol 。您需要将文本视图的可编辑属性设置为

UILabel doesn't have any methods for doing this. You can do it with UITextView, because it implements the UITextInput protocol. You will want to set the text view's editable property to NO.

像这个未经测试的代码应该可以工作:

Something like this untested code should work:

- (CGRect)rectInTextView:(UITextView *)textView stringRange:(CFRange)stringRange {
    UITextPosition *begin = [textView positionFromPosition:textView.beginningOfDocument offset:stringRange.location];
    UITextPosition *end = [textView positionFromPosition:begin offset:stringRange.length];
    UITextRange *textRange = [textView textRangeFromPosition:begin toPosition:end];
    return [textView firstRectForRange:textRange];
}

这应返回 CGRect (在文本视图的坐标系中),涵盖 stringRange 指定的子字符串。如果您将按钮设置为文本视图的子视图,则可以将按钮的框架设置为此矩​​形。

That should return a CGRect (in the text view's coordinate system) that covers the substring specified by stringRange. You can set the button's frame to this rectangle, if you make the button a subview of the text view.

如果子字符串跨越多行,则矩形将仅覆盖第一行。

If the substring spans multiple lines, the rectangle will only cover the first line.

这篇关于找到uilabel中文本的位置{x,y}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆