NSTableView - Table Column with rich formatted text and image

半腔热情 提交于 2019-12-21 21:28:17

问题


I am new with Cocoa and I want to display one-column NSTableView with multiline rich-formatted (different fonts and colors within one cell) and images. Is the NSTableView a good choice for this task ?

If it how can i get it ? Do I need to use NSCell control ? I will be thankful for good stating tutorial and examples. I have tried to google it, but not find something useful.


回答1:


Cell-based table view approach

With a cell-based table view you can't do this because the standard cell NSImageCell and NSTextCell can only display an image or text. You could make your down subclass of NSCell to make a cell that accepts both a image and text, for example, Display icon and text in same cell of NSTableView. To display different fonts and colors you will need to use a NSAttributedString for example, (no checked this code Xcode so there could be a few bugs, but it 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])];

View-based table view approach

View-based table view display NSTableCellView views in their the table cells. The standard NSTableCellView has a imageView and textField property so for your purpose this would seem like an ideal fit. Simply set the table view cell's image view to display your image, tableCellView.imageView.image = myImageset then set the text you want to display in the text field, tableCellView.textField.attributeStringValue = myAttributedString. Note you will have to use an attributed string to get the different colours and fonts (see above).



来源:https://stackoverflow.com/questions/25043090/nstableview-table-column-with-rich-formatted-text-and-image

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