0

我有一些来自服务器的文本。它可以是单行或多行文本。我必须在 UILabel 上显示文本,这对我来说没问题。问题是,我必须在查找相同文本的特定子字符串时显示 UIButton。例如文本是Nitish\n435-234-6543\nIndia,显示如下:

Nitish  
435-234-6543  
India  

因此,当我找到435-234-6543时,我必须在435-234-6543上显示 UIButton 。

笔记:

  1. 文本是动态的 - 来自服务器。以上只是一个例子。
  2. UIButton 将是 UILabel 的子视图。

我尝试了不同的方法例如OHAttributedLabelrectForLetterAtIndex等等。但没有获得成功。我的想法是,在找到子字符串时创建按钮并根据子字符串的NSRange设置按钮的框架。这是一种可能吗?如何做呢?还是有其他方法可以做到这一点?

我想这是我担心的方法。

4

3 回答 3

0

1)简单的解决方案:

制作UILabel一个 UITextView 并使用该属性dataDetectorTypes自动将电话号码作为链接。


2)更多涉及的解决方案:

有一种方便的方法可以确定需要绘制的任何文本的大小:

CGSize size = [label.text sizeWithFont:label.font 
                     constrainedToSize:CGSizeMake(label.frame.size.width, CGFLOAT_MAX) 
                         lineBreakMode:UILineBreakModeWordWrap];

您现在可以通过将字符串拆分为其行来确定哪个字段是电话号码:

NSArray *comp = [label.text componentsSeparatedByString:@"\n"];

然后检查哪一个是数字。现在你必须从height你的size变量中计算出精确的帧,可能是这样的:

CGFloat positionOfNumber; // the index of your line in comp cast to CGFloat
CGFloat buffer = 10; // fiddle with this
CGFloat buttonHeight = (size.height- 2*buffer)/[comp length];
CGFloat buttonY = buffer + positionOfNumber * buttonHeight;
CGRect buttonFrame = CGRectMake(0, buttonY, label.frame.size.width, buttonHeight); 
于 2012-01-14T09:32:20.533 回答
0

-->我试图计算位置但没有成功。计算位置似乎需要做很多工作。我想到的一个直接解决方案是你为什么不拿一两个标签和一个按钮。

认为。您从 web 服务获得的动态字符串是:“Nitesh-56789-Test”。

  1. 查找字符串范围假设即“56789”。
  2. 该范围的起始位置之前的字符串分配给一个标签,即将“Nitesh”分配给标签一个。
  3. 现在添加一个自定义按钮,将我们搜索的字符串作为文本 (56789)。
  4. Now make sure in main string there something after our substring or not. Here I mean after our search string "56789" still "Test" remain so assign it to third lable.


Here you have to figue out frame of all labels and button using dynamic height width calculation by using sizeWithFont method.

于 2012-01-14T10:28:57.470 回答
0

For those who want perfect solution here's the solution on how to get CGRect of a substring.

于 2015-09-08T07:25:01.367 回答