NSTableView - Table Column with Rich Formatted Text and Image

I'm new to Cocoa, and I want to display a single column NSTableView with multi-line formatted (different fonts and colors inside the same cell) and images. Is NSTableView a good choice for this task?

If it is, how can I get it? Do I need to use an NSCell control? I will be grateful for the good guidance and examples. I tried to do this, but did not find anything useful.

+1
source share
1 answer

Cell Based Table Approach

You cannot do this with a table view on a cell, because the standard cell NSImageCell and NSTextCell can only display image or text. You can make your lower subclass NSCell to make a cell that accepts both the image and the text, for example Show icon and text in one NSTableView cell . To display different fonts and colors, you need to use, for example, NSAttributedString (did not check this Xcode, so there may be a few errors, but this gives you an idea),

 NSString *redWord = @"Hello"; NSString *greenWord = @"World"; NSString *message = [NSString stringWithFormat:@"%@ %@", redWord, greenWord]; NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString:message]; [text addAttribute:NSForegroundColorAttributeName value:[NSColor redColor] range:NSMakeRange(0, [redWord length])]; [text addAttribute:NSFontAttributeName value:[NSFont fontWithName:@"Arial Italic" size:12]; range:NSMakeRange(0, [redWord length])]; [text addAttribute:NSForegroundColorAttributeName value:[NSColor greenColor] range:NSMakeRange([redWord length] + 1, [greenWord length])]; [text addAttribute:NSFontAttributeName value:[NSFont fontWithName:@"Times Bold" size:12]; range:NSMakeRange([redWord length] + 1, [greenWord length])]; 

Presentation-based table view approach

Display a table view as NSTableCellView tables in its table cells. The standard NSTableCellView has an imageView and textField , so it will look perfect for your purpose. Just set the image view of the table cell to display the image, tableCellView.imageView.image = myImageset then set the text you want to display in the text box, tableCellView.textField.attributeStringValue = myAttributedString . Please note that you will have to use the attributed string to get different colors and fonts (see above).

+4
source

Source: https://habr.com/ru/post/1202605/


All Articles