添加tap事件到IOS NSMutableAttributedString



我有一个NSMutableAttributedString,如"Bob like your picture"。

我想知道我是否可以为"Bob"one_answers"picture"添加两个不同的点击事件。理想情况下,点击"Bob"将显示一个带有Bob的配置文件的新视图控制器,点击"picture"将显示一个带有图片的新视图控制器。我可以用NSMutableAttributedString做这个吗?

您可以通过使用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管理的

我处理它的方式是在UITextView中使用标准NSString。然后利用UITextInput协议方法firstRectForRange:。然后你可以很容易地在矩形中覆盖一个不可见的UIButton,并处理你想要采取的行动。

最新更新