简体   繁体   中英

Cocoa: How to make table view draw custom views in each cell

I am learning Cocoa and trying to create an application for Mac that displays a simple book list. Each book is an NSView with its cover image, title and author. I want to present this list as a NSTableView with a single column and a book view in each cell. However i can't yet figure out how to display a custom view inside a table cell in interface builder or programmatically. Any tips would be very appreciated :)

Inso.

If all of your "book views" are the same size, why not use NSCollectionView / NSCollectionViewItem ? It's a much cleaner solution (provided they're all sized the same).

Assuming a collection view wouldn't be a better solution, what you need to do is to write a custom cell. The column owns exactly one such cell, which the table view will use to draw the column's value for each row.

(If you came from the iPhone, yes, this is completely different from UITableView. Each NSTableColumn has exactly one cell, which it uses for every row.)

If you're using your NSView class somewhere else, then you could make it into a subclass of NSControl and have it use another instance of the same cell class. Like most controls, all the real work would be done by the cell, which enables you to reuse that behavior in multiple controls (your single control and your table view).

See Control and Cell Programming Topics for more info.

Apple added view-based table views in Lion, so you should be able do this natively with NSTableView, now.

(You still can't put an NSView in an NSCell—that wouldn't make sense. But you can have views instead of cells in a table view.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM