在 NSRange 的帮助下在子字符串上创建 UIButton
我有一些来自服务器的文本。它可以是单行或多行文本。我必须在 UILabel 上显示文本,这对我来说没有问题。问题是,我必须在查找同一文本的特定子字符串时显示 UIButton。例如,文本是 Nitish\n435-234-6543\nIndia ,显示如下:
Nitish
435-234-6543
India
因此,当我找到 435-234-6543 时,我必须显示 UIButton 435-234-6543。
注意:
- 文本是动态的 - 来自服务器。以上仅是一个示例。
- UIButton 将是 UILabel 的子视图。
我尝试了不同的方法,例如 OHAttributedLabel、rectForLetterAtIndex 和 这个也是如此。但没有获得成功。我的想法是,在找到子字符串时创建按钮,并根据子字符串的 NSRange 设置按钮的框架。这有可能吗?怎么办呢?或者还有其他方法可以做到这一点吗?
我想这就是我担心的方法。
I have some text coming from server. It may be single line or multiline text. I have to display the text on UILabel, which is no problem for me. The problem is, I have to display UIButton on finding a particular substring of the same text. For example the text is Nitish\n435-234-6543\nIndia which is being displayed as follows :
Nitish
435-234-6543
India
So, when I find 435-234-6543 I have to display UIButton on 435-234-6543.
Notes:
- The text is dynamic - coming from server. Above is only an example.
- UIButton will be a subview of UILabel.
I tried different ways like OHAttributedLabel, rectForLetterAtIndex and this too. But not getting success. What my idea is, to create the button when substring is found and to set the frame of button based on NSRange of substring. Is this a possibility? How can it be done? Or is there some other way to do this?
I guess it is the approach I am worried about.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于那些想要完美解决方案的人,这里有关于如何获取子字符串的 CGRect 的解决方案。
For those who want perfect solution here's the solution on how to get CGRect of a substring.
-->我尝试计算位置但没有成功。计算位置似乎需要做很多工作。我想到的一个直接解决方案是为什么不拿一两个标签和一个按钮。
认为。您从网络服务获得的动态字符串是:“Nitesh-56789-Test”。
在这里,您必须使用动态高度计算出所有标签和按钮的框架使用 sizeWithFont 方法计算宽度。
-->I have tried to calcluate position but didnt get success. Seems lots of work to calcualate position. One immediate solution come to my mind is why are you not taking one or two labels and one button.
Suppose. You got dynamic string from webservice is: "Nitesh-56789-Test".
Here you have to figue out frame of all labels and button using dynamic height width calculation by using sizeWithFont method.
1) 简单的解决方案:
将您的
UILabel
设为UITextView,并使用属性dataDetectorTypes
自动将电话号码作为链接。2)更复杂的解决方案:
有一种方便的方法来确定需要绘制的任何文本的大小:
您现在可以通过将字符串拆分为几行来确定哪个字段是电话号码:
和然后检查哪个是数字。现在,您必须根据
size
变量的height
计算准确的框架,可能如下所示:1) Easy solution:
Make your
UILabel
a UITextView and use the propertydataDetectorTypes
to have phone numbers as links automatically.2) More involved solution:
There is a convenient method to determine the size any text will need to be drawn:
You could now determine which field is the phone number by splitting the string into its lines with:
and then checking which one is numeric. Now you would have to calculate the exact frame from the
height
of yoursize
variable, maybe like this: