Search code examples
iphoneiosbuttonhyperlinkdrawrect

Clickable text in -drawRect:


I am drawing a string in a UIView using -drawRect:. This string may contain links and I would like to make these links a different color and make them clickable.

Does anyone know the best (and easiest) way to do this? I am fearing that I will have to filter the links out of the string, create buttons for the links and then position the different parts of the string including the buttons manually.

This is my code in -drawRect:

NSString *message = [cellData objectForKey:@"message"];
CGSize messageLabelSize = [sizeCalc sizeOfMessageLabel:message];
[message drawInRect:CGRectMake(kBoxPadding + kProfilePicWidth + kBoxPadding, kBoxPadding + nameLabelSize.height + kSpacingNameToMessage - kContentOffset, messageLabelSize.width, messageLabelSize.height) withFont:[UIFont fontWithName:@"Helvetica" size:13]];

My message string could look like this:

"This is a test text and it has a link http://google.com/ in the middle."

I would like the result to look a bit like the above where http://google.com/ is a hyperlink.


Solution

  • You can't from a drawRect because that just draw graphics, you need a subview:

    NSString *message = @"This is a test text and it has a link http://google.com/ in the middle.";
    CGSize size = [message sizeWithFont:[UIFont boldSystemFontOfSize:11.0]]
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake (0, 0, size.width, size.height)]; 
    textVioew.editable = NO;
    [textView setDataDetectorTypes:UIDataDetectorTypeLink];
    [textView setText:message];
    [self.view addSubview:textView];
    [textView release];