Clickable url link in NSTextFieldCell inside NSTableView?

依然范特西╮ 提交于 2019-12-03 15:50:59

I don't think the tech note answers the question, which was how to put a link in an NSTableView cell. The best way I've found to do this is to use a button cell for the table cell. This assumes that only links will be in a particular column of the table.

In Interface Builder, drag an NSButton cell onto the table column where you want the links.

In your table view delegate, implement tableView:dataCellForTableColumn:row: as follows:

- (NSCell *) tableView: (NSTableView *) tableView
    dataCellForTableColumn: (NSTableColumn *) column
    row: (NSInteger) row
{
    NSButtonCell *buttonCell = nil;
    NSAttributedString *title = nil;
    NSString *link = nil;
    NSDictionary *attributes = nil;

// Cell for entire row -- we don't do headers
    if (column == nil)
        return(nil);

// Columns other than link do the normal thing
    if (![self isLinkColumn:column]) // Implement this as appropriate for your table
        return([column dataCellForRow:row]);

// If no link, no button, just a blank text field
    if ((link = [self linkForRow:row]) != nil) // Implement this as appropriate for your table
        return([[[NSTextFieldCell alloc] initTextCell:@""] autorelease]);

// It's a link. Create the title
    attributes = [[NSDictionary alloc] initWithObjectsAndKeys:
        [NSFont systemFontOfSize:[NSFont systemFontSize]], NSFontAttributeName,
        [NSNumber numberWithInt:NSUnderlineStyleSingle], NSUnderlineStyleAttributeName,
        [NSColor blueColor], NSForegroundColorAttributeName,
        [NSURL URLWithString:link], NSLinkAttributeName, nil];
    title = [[NSAttributedString alloc] initWithString:link attributes:attributes];
    [attributes release];

// Create a button cell
    buttonCell = [[[NSButtonCell alloc] init] autorelease];
    [buttonCell setBezelStyle:NSRoundedBezelStyle];
    [buttonCell setButtonType:NSMomentaryPushInButton];
    [buttonCell setBordered:NO]; // Don't want a bordered button
    [buttonCell setAttributedTitle:title];
    [title release];
    return(buttonCell);
}

Set the target/action for the table to your delegate and check for clicks on the link column:

- (void) clickTable: (NSTableView *) sender
{
    NSTableColumn *column = [[sender tableColumns] objectAtIndex:[sender clickedColumn]];
    NSInteger row = [sender clickedRow];
    NSString *link = nil;

    if ([self isLinkColumn:column] && (link = [self linkForRow:row]) != nil)
        [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:link]];
}

Now the link looks like a link, but a click on it is actually a button press, which you detect in the action method and dispatch using NSWorkspace.

Have you seen this technical note from Apple regarding hyperlinks?

Embedding Hyperlinks in NSTextField and NSTextView

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!