使用NSString附加UIButton

时间:2012-04-22 16:22:58

标签: iphone ios nsstring uibutton nsarray

我有这段代码在SQLite DB的textview中显示一些文本..

NSMutableString *combined = [NSMutableString string];
for(NSUInteger idx = 0; idx < [delegate.allSelectedVerseEnglish count]; idx++) {
    [combined appendFormat:@" %d   %@", idx, [delegate.allSelectedVerseEnglish objectAtIndex:idx]];
}

self.multiPageView.text = combined;
self.multiPageView.font = [UIFont fontWithName:@"Georgia" size:self.fontSize];

delegate.allSelectedVerseEnglishNSArray multiPageViewUITextView

我把上面的循环函数用于根据文本获取Numbers,例如1 hello 2 iPhone 3 iPad 4 mac etc etc..我只想在文本而不是1 2 3 4 ..之间使用 UIButton ,例如我想要的unbutton hello unbutton iPhone etc etc。因为我需要从中做一些触摸事件。如何做到这一点? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

如果要在文本视图中的某些文本之间放置UIButton,除了将其作为单独的视图放在上面之外别无他法。因此,您需要在这些按钮下方添加空格,这些空间应根据按钮的大小自行计算。 所以,如果你想看到这样的东西:

Press here [UIButton] or here [Another UIButton],

您的文字字符串应如下所示

Press here            or here                   ,

因此,当您在这些地方添加按钮时,它看起来就像您希望的那样。

更新

似乎我们需要更多代码,所以这里是: 首先,您需要计算一个字母的大小。我们假设它是10像素高度和8像素。不,我们只是称之为 letterHeight letterWidth 。我们还假设您需要64x10像素的按钮。所以,我们将需要64/8 = 8 + 2个空格来支持该按钮(2个围绕它的边框) 所以,我们走了

NSMutableString *combined = [NSMutableString string];
int letterHeight = 10;
int letterWidth = 8;
   for(NSString *verse in delegate.allSelectedVerseEnglish) {
       [combined appendFormat:@"          %@",verse];//10 spaces there
//You have to experiment with this, but idea is that your x coordinate is just proportional to the length of the line you are inserting your button in, and y is proportional to number of lines
    int xCoordinate = [combined length]*letterWidth%(int)(self.multiPageView.frame.size.width);
    int yCoordinate = [combined length]*letterWidth/(int)(self.multiPageView.frame.size.width)*letterHeight;

     UIButton *newButton = [[UIButton alloc]initWithFrame:CGRectMake(xCoordinate,yCoordinate,64,10)];
     [self.multiPageView addSubview:newButton];
}
 self.multiPageView.text = combined;