2013-03-18 505 views
2

我有一個NSMutableAttributedString,比如「Bob喜歡你的圖片」。將點擊事件添加到IOS NSMutableAttributedString

我想知道如果我可以添加兩個不同的點擊事件「鮑勃」和「圖片」。理想情況下,點擊「Bob」會爲Bob的配置文件提供一個新的視圖控制器,點擊「圖片」會爲該圖片提供一個新的視圖控制器。我可以用NSMutableAttributedString來做到這一點嗎?

回答

1

我會處理它的方式是在UITextView中使用標準NSString。然後利用UITextInput協議方法firstRectForRange:。然後,您可以輕鬆地在該矩形上覆蓋一個隱形UIButton並處理您想要採取的操作。

+0

這很容易做到。謝謝! – zhengwx 2013-03-18 23:47:18

10

你可以通過使用CoreText實現一個方法來獲取用戶選擇/觸摸的字符的索引。首先,使用CoreText,在自定義UIView子類中繪製屬性字符串。一個例子覆蓋drawRect:方法:

- (void) drawRect:(CGRect)rect 
{ 
    // Flip the coordinate system as CoreText's origin starts in the lower left corner 
    CGContextRef context = UIGraphicsGetCurrentContext(); 

    CGContextTranslateCTM(context, 0.0f, self.bounds.size.height); 
    CGContextScaleCTM(context, 1.0f, -1.0f); 

    UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.bounds]; 
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)(_attributedString)); 

    if(textFrame != nil) { 
     CFRelease(textFrame); 
    } 

    // Keep the text frame around. 
    textFrame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path.CGPath, NULL); 
    CFRetain(textFrame); 

    CTFrameDraw(textFrame, context); 
} 

其次,創建一個詢問文本找到一個給定的點字索引的方法:

- (int) indexAtPoint:(CGPoint)point 
{ 
    // Flip the point because the coordinate system is flipped. 
    point = CGPointMake(point.x, CGRectGetMaxY(self.bounds) - point.y); 
    NSArray *lines = (__bridge NSArray *) (CTFrameGetLines(textFrame)); 

    CGPoint origins[lines.count]; 
    CTFrameGetLineOrigins(textFrame, CFRangeMake(0, lines.count), origins); 

    for(int i = 0; i < lines.count; i++) { 
     if(point.y > origins[i].y) { 
      CTLineRef line = (__bridge CTLineRef)([lines objectAtIndex:i]); 
      return CTLineGetStringIndexForPosition(line, point); 
     } 
    } 

    return 0; 
} 

最後,你可以重寫touchesBegan:withEvent:方法來獲取用戶觸摸位置並將其轉換爲字符索引或範圍:

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *t = [touches anyObject]; 
    CGPoint tp = [t locationInView:self]; 
    int index = [self indexAtPoint:tp]; 

    NSLog(@"Character touched : %d", index); 
} 

一定要將CoreText包含在到你的項目,並清理任何資源(如文本框),因爲內存不受ARC管理。

+0

這對我來說太複雜了。但謝謝你的答案! – zhengwx 2013-03-18 23:48:07

相關問題