Document translation -Collection View – 1.2

Design your data sources and delegates

Any collection view must have a data source object. This data source object is what your app displays. It can be an object from a data model of your app, or a controller that manages the collection view. The only requirement of the data source is that it must be able to provide the information needed for the collection view, such as how many items it has and what views to use when displaying the items. The
delegate object is an optional (but recommended) object for managing aspects related to presentation and interaction of content. Although the delegate’s primary responsibility is to manage the highlighting and selection of cell, it can also be extended to provide additional information. For example, streaming layouts extend several delegate behaviors from defining layout metrics, such as the size of cells and the spacing between them.

The data source manages your content

The data source object’s responsibility is to manage what you are going to use the collection view to render. The data source object must adhere to the UICollectionViewDataSource protocol, which defines the basic behavior and methods you have to support. The job of the data source is to provide answers to the following questions in the set view:

  • How many partitions are included in the collection view?
  • For a given partition, how many items does that partition contain?
  • What views should be used to display the appropriate content for a given partition and item?

Partitioning and items are the basic organizational principles for collection view content. A collection view usually has at least one partition, and there may be more partitions. Each partition contains 0 or more items. Items stands for the main content you want to render, and partitions organize these items into logical groups. For example, a photo app might use a partition to represent a photo album or a set of photos taken on the same day.

Collection view refers to the data contained in the NSIndexPath object. When you try to locate a item, the collection view provides index path information to it through the layout object. For items, the index path contains a partition number and a item number. For supplementary and decorated views, the index path contains all the values provided by the layout object. The meaning of the indexed path attached to the supplemental and ornamental views depends on your app, even though the first index corresponds to a particular partition in the data source. The index paths of these views are more marked rather than meaningful, determining what view is currently being considered. Thus, for example, if you have additional views to create headers and footers for partitions, you can see in the flow layout that the relevant information provided by the index path is a partitioning reference.

Note: Although the standard indexing path supports multiple levels, the cells of the collection view supports only two levels of indexing paths with section and item, which are similar to the index path of the UITableView class. Additional views and decorative views can have more complex indexing paths if needed. The element whose index path is greater than 1 is interpreted as a partition corresponding to the first index in the path. Traditionally, only second indexes are necessary, but supplemental and decorative views are not limited to two. Keep that in mind when designing data sources.

No matter how you arrange partitions and items on your data objects, the visual rendering of these partitions and items is still determined by the layout object. Different layout objects can render partitions and item data very differently, as shown in figure 2-1. In this diagram, a stream layout object vertically arranges each partition, each of which is the same as the previous partition. Custom layout objects can partition the partitions in a non-linear layout and demonstrate again the separation between layout and actual data.

Document translation -Collection View - 1.2,
, Figure 2-1
Design data object

Valid data sources use partitions and items to help organize their underlying data objects. Organize your data into partitions and items to make it easier to implement your data source approach later. And since your data source methods are frequently invoked, you want to make sure that the implementations of these methods can access data as quickly as possible.
a simple solution (but not the only solution) is to use a nested array for your data source, as shown in figure 2-2. In this configuration, the top-level array contains one or more arrays representing the partitions of the data source. Each partition array contains the items data within that partition. Finding item in a partition is a partition array that gets it, and then gets the item problem from that array. This type of arrangement makes it easy to manage an appropriately sized items collection and retrieves a single item as needed.

Document translation -Collection View - 1.2,
, figure 2-2

When designing your data structure, you can always start with a simple array and move to a more efficient structure as needed. In general, your data object should not be a performance bottleneck. The collection view usually accesses the data source, counts only a total of several objects, and retrieves the views of the elements on the current screen. If the layout object relies only on data from the data object, performance can be seriously affected when the data source contains thousands of objects.

Tell the collection view of your content

The question of your data source from the collection view is how many partitions it contains and how many items are included in each partition. When the following actions occur, the collection view will ask your data source to provide this information:

  • Collection view for the first time
  • Assign a different data source object to the collection view
  • Specifies the reloadData method that calls the collection view
  • The collection view uses performBatchUpdates:completion: or any move, add, delete method to execute a block

You use the numberOfSectionsInCollectionView: method to provide the number of partitions, and the collectionView:numberOfItemsInSection: method is used to provide the number of items in each partition. You have to implement the collectionView:numberOfItemsInSection: method, but if your collection view has only one partition, the implementation of the numberOfSectionsInCollectionView: method is optional. The two method returns the integer value of the appropriate information.
if you implement the data source as shown in Figure 2-2, the implementation of your data source method might be as simple as listing 2-1 shows. In these code, the _data variable is the custom member variable of the data source that stores the top level array of the partition. Getting the count of the array will produce the number of partitions. Getting the count in its subarray will produce the number of items in the partition. Of course, your own code should be checked for errors to make sure that the returned value is valid.

//Listing 2-1 Providing the section and item counts (NSInteger) numberOfSectionsInCollectionView: (UICollectionView*) collectionView is a class {/ / _data member variable that contains one array per section. return [_data count];} - (NSInteger) collectionView: (UICollectionView*) collectionView numberOfItemsInSection: (NSInteger section) {NSArray* sectionArray = [_data objectAtIndex:section]; return [sectionArray count];}
Configuring cells and supplementary views

Another important task of your data source is to provide a collection view that displays the views of your content. The collection view does not track the contents of your app. It requires only the views you give, and applies the current layout information to them. Therefore, all of the content displayed on the view is your responsibility. When
reports how many partitions and items it manages in your data source, the collection view requires layout objects to provide layout properties for the collection view content. At some point, the collection view requires the layout object to provide a list of elements in a particular rectangle (usually a visible rectangle). The collection view uses this list to query your data source for the corresponding cells and supplementary views. In order to provide these cells and supplementary views, your code must do the following:

  1. Embed your template cell and view into the storyboard file (or register a class or NIB file for each supported cell or view)
  2. In your data source, when asked out and configure the cell or view the corresponding

To ensure that cell and supplementary views are used in the most efficient way, the collection view assumes responsibility for creating these objects for you. Each collection view maintains the internal queue of the currently unused cells and supplementary views. Instead of creating objects yourself, simply ask the collection view to provide the view you want. If one is waiting in the reuse queue, the collection view will be ready and returned to you quickly. If you are not waiting, the collection view creates a new one using the registered class or NIB file and returns it to you. So, every time you retrieve a cell or view, you always get a ready-made object. The
reuse identifier makes it possible to register multiple types of cells and multiple types of supplementary views. The reuse identifier is a string used to distinguish between the registered cell and the view type. The contents of a string are only relevant to the data source object. But when you request a view or cell, you can use the supplied index path to determine which type of view or cell you want, and then get it by the appropriate reuse notation.

Sign up for your cells and supplementary views

You can configure the cells and view of the collection view in code or in the storyboard file.
configure the cells and views in the storyboard. When configuring cells and supplementary views in the storyboard, you can drag and drop item to the set view and configure it. This creates a relationship between the collection view and the corresponding cells or view.

  • For cells, drag and drop a CollectionViewCell in the object library and place it in the collection view. Set the custom class and collection view view identifier of the cell to the appropriate value.
  • For the supplementary view, drag and drop a CollectionReusableView in the object library and place it in the collection view. Sets the view’s custom classes and collections of reusable view identifiers to appropriate values.

Configuring cells with code. Use the registerClass:forCellWithReuseIdentifier: method or the registerNib:forCellWithReuseIdentifier: method to associate your cell with the reuse identifier. You can be a part of these methods that father view controller initialization process.
configuring supplemental views with code. Use the registerClass:forSupplementaryViewOfKind:withReuseIdentifier: method or the registerNib:forSupplementaryViewOfKind:withReuseIdentifier: method to associate a type view with a reuse identifier. You can be a part of these methods that father view controller initialization process. Although
uses only one reuse identifier to register cells, the supplementary view requires an additional identifier called a type string. Each layout object is responsible for defining the kinds of supplementary views that it supports. For example, the UICollectionViewFlowLayout class supports two types of supplementary Views: partitioned head view and partitioned footer view. To identify the two types of views, it defines string constants UICollectionElementKindSectionHeader and UICollectionElementKindSectionFooter. In layout, the layout object contains the type string for the other layout attributes of the view type. The collection view then passes the information to the data source. Then, the data source type string and reuse identifier to determine which object is used to return and out of view.

Note: if you implement your own custom layout, you are responsible for defining the kinds of supplementary views that your layout supports. A layout can support multiple supplementary views, each of which has its own type string. For more information about custom layouts, see Creating Custom Layouts.

Registration is a one-time event, you must be in the cells or out of view before the occurrence of intention. Already after registration, you can according to the needs of out of any number of cells or view, without the need to re register them. Not to recommend the registration information in the list of one or more items after the change. It’s better to just register your cells and view once and complete it.

The column and configure the cells and view

Your data source object is responsible for providing cells and supplementary views when asked about them in a collection view. The UICollectionViewDataSource protocol contains two methods for this purpose: collectionView:cellForItemAtIndexPath: and collectionView:viewForSupplementaryElementOfKind:atIndexPath. Because cells is an essential element of the collection view, your data source object must implement the collectionView:cellForItemAtIndexPath: method, but the collectionView:viewForSupplementaryElementOfKind:atIndexPath: is optional, depending on the type of layout used. In these two cases, you implement these methods in a very simple fashion:

  1. The use of dequeueReusableCellWithReuseIdentifier:forIndexPath: or dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath: out of a cell or the right type of view.
  2. Configure the view using data from a specific index path.
  3. Return this view.

The purpose is to reduce the out process you must create a cell or view the responsibility. As long as you have registered a cell or view, out of process guarantee does not return nil. If there is no cell or a given type of view in a reuse queue, the story board is out method will use your registration or use your class or simply create a nib file.
returns from out of process cell should be in the original state, and prepare for the new configuration data. For the cell or view must be created, out of process using the normal process to create and initialize it – that is to say, by loading from the storyboard or NIB file view, or by creating a new instance and the initWithFrame: method is used to initialize. In contrast, there are no newly created data items, but entries from a reuse queue may already contain previously used data. In this case, the column will call to the prepareForReuse method, let it have the opportunity to return to the original state of entry. When you implement a custom cell or view class, you can override that method to reset the property to the default value and perform any other cleanup.
when the data source column view, it will use the new data to configure the view. You can use the index path passed to the data source method to locate the appropriate data object, and then apply the object’s data to the view. After configuring the view, return it from the method and complete it. Listing 2-2 shows a simple example of how to configure a cell. In the cell column, the location information using the cell method to set the cell custom tag, and then return to the cell.

//Listing 2-2 Configuring a custom cell (UICollectionViewCell) collectionView: (UICollectionView * collectionView) cellForItemAtIndexPath: (NSIndexPath * indexPath) {MyCustomCell* newCell = [self.collectionView dequeueReusableCellWithReuseIdentifier:MyCellID forIndexPath:indexPath]; newCell.cellLabel.text [NSString stringWithFormat:@ = "Section:%d Item:%d", indexPath.section, indexPath.item]; return newCell;}

Note: when a view is returned from the data source, a valid view is always returned. Even if you can’t display the requested view and return nil for some reason, the assertion will result and the application terminates because the layout object expects to return a valid view through this method.

Insert, delete and move partitions and items

To insert, delete, or delete a separate partition or item, follow these steps:

  1. Update data on the data source object.
  2. The appropriate method to call the collection view to insert or delete the partition or item.

It is important to update the data source before any changes to the collection view are notified. The collection view method assumes that your data source contains the current correct data. If not, the collection view may receive an incorrect items collection from your data source, or ask for a nonexistent items and cause the application to crash.
when you programmatically add, delete, or move a single item, the collection view automatically creates animations to react to changes. If you want to animate multiple changes together, you must complete all the insertion, deletion, or movement calls within a block, and through the block performBatchUpdates:completion: method. The batch update process will then animate all the changes at the same time. You can freely mix, tune, insert, delete, or move items in the same block.
listing 2-3 shows a simple example of how to execute a batch update to delete the currently selected items. In the performBatchUpdates:completion: method, the block first calls the custom method to update the data source. Then tell the collection view to delete these items. The updates you provide and the complete block will execute synchronously with block.

//Listing 2-3 Deleting the selected items [self.collectionView performBatchUpdates:^{NSArray* itemPaths = [self.collectionView indexPathsForSelectedItems] the items from the; / / Delete data source. [self deleteItemsFromDataSourceAtIndexPaths:itemPaths] delete the items; / / Now from the collection view. [self.collectionView deleteItemsAtIndexPaths:itemPaths] completion:nil];};
Manages the selection and highlighting of visual states

The set view supports individual selection by default, and can be configured to support multiple choice or disable selection altogether. Detection of the collection view within the boundaries of the tap and highlight or select the appropriate cell. In most cases, the collection view modifies only the properties of the cell to indicate that it is checked or highlighted; it does not change the visual appearance of the cell, with one exception. If the selectedBackgroundView property of cell contains a valid view, the collection view displays the view when the cell is highlighted or checked. The
listing 2-4 shows the code that can be implemented in the custom collection view cell to highlight, highlight, and select the changing appearance of the state. When cell is first loaded and when cell is not highlighted or unchecked, the backgroundView attribute of cell is always a default view. Once the cell is highlighted or checked, the selectedBackgroundView property replaces the default background view. In this case, the background color of the cell changes from red to white when selected or highlighted.

//Listing 2-4 Setting the background views to indicate changed states UIView* backgroundView = [[UIView alloc] initWithFrame:self.bounds]; backgroundView.backgroundColor [UIColor = redColor]; self.backgroundView = backgroundView; UIView* = selectedBGView [[UIView alloc] initWithFrame:self.bounds]; selectedBGView.backgroundColor [UIColor = whiteColor]; self.selectedBackgroundView = selectedBGView;

The agents of the collection view use the following methods to provide a collection view for highlight and selection:

  • CollectionView:shouldSelectItemAtIndexPath:
  • CollectionView:shouldDeselectItemAtIndexPath:
  • CollectionView:didSelectItemAtIndexPath:
  • CollectionView:didDeselectItemAtIndexPath:
  • CollectionView:shouldHighlightItemAtIndexPath:
  • CollectionView:didHighlightItemAtIndexPath:
  • CollectionView:didUnhighlightItemAtIndexPath:

These methods provide you with many opportunities to adjust the precise specification behavior required for the highlight / selection collection view.
, for example, if you like to draw a cell selection for yourself, you can set the selectedBackgroundView property to nil and apply any visual changes to your proxy object to the cell. You can apply visual changes in the collectionView:didSelectItemAtIndexPath: method and remove them in the collectionView:didDeselectItemAtIndexPath: method.
if you love yourself to draw the bright state, you can override the collectionView:didHighlightItemAtIndexPath: method and the collectionView:didUnhighlightItemAtIndexPath: agent, and use them to use your highlight. If you also specify a view in the selectedBackgroundView property, you should make changes to the content view of the cell to make sure the changes are visible. Listing 2-5 shows a simple way to use the content view, background color, change, highlight, and display.

//Listing 2-5 Applying a temporary highlight to a cell (void) collectionView: (UICollectionView * colView) didHighlightItemAtIndexPath: (NSIndexPath * indexPath) {UICollectionViewCell* cell = [colView cell.contentView.backgroundColor = cellForItemAtIndexPath:indexPath]; [UIColor blueColor];} - (void) collectionView: (UICollectionView * colView) didUnhighlightItemAtIndexPath: (NSIndexPath * indexPath) {UICollectionViewCell* cell [colView = cellForItemAtIndexPath:indexPath]; cell.contentView.backgroundColor = nil};

There are subtle but important differences between the highlight and selected states of the cell. The highlight state is a transient state, and when the user’s fingers are still touching the device, you can highlight the application to the cell. This state is set to YES when the collection view is tracking the touch event on the cell. When the touch event stops, the highlight state returns the value of NO. In contrast, the selected state changes only after a series of touch events – specifically, when these events indicate that the user is trying to select cell.
figure 2-3 illustrates a series of steps that occur when a user touches an unselected cell. The initial press event causes the collection view to change the highlight state of the cell to YES, even if doing so does not automatically change the appearance of the cell. If the final lift event occurs on the cell, the highlight state returns NO, and the collection view changes the selected state to YES. When the user changes the selected state, the collection view displays the view on the selectedBackgroundView property of the cell, but this is the only visual change that the collection view has to the cell. Other visual changes must be done through your proxy object.

Document translation -Collection View - 1.2,
, figure 2-3

Whether the user chooses or deselect cell, the selected state of the cell is always changed by the last thing.
cell clicks first and always changes the highlight status of cell. The selected status of cell is changed only after clicking the series event and applying it to any highlight. When designing your cell, you should ensure that the visual appearance of your highlighted and selected states does not cause unexpected collisions.

Show the edit menu to cell

When the user performs a long pressing gesture on the cell, the collection view displays an edit menu for cell. This edit menu can be used to cut, copy, and paste cells in the collection view. Several requirements must be met before the edit menu is displayed:

  • The agent must implement three methods associated with processing operations: collectionView:shouldShowMenuForItemAtIndexPath: collectionView:canPerformAction:forItemAtIndexPath:withSender: collectionView:performAction:forItemAtIndexPath:withSender:
  • The collectionView:shouldShowMenuForItemAtIndexPath: method must return YES for the specified cell
  • The collectionView:canPerformAction:forItemAtIndexPath:withSender: method must return YES for at least one desired operation. The collection view supports the following actions:
    , cut:,
    , copy:,
    , paste:

If these conditions are met, and the user from the menu, select a set of methods of operation, collectionView:performAction:forItemAtIndexPath:withSender: will call the agent view to perform operations at the specified cell.
listing 2-6 shows how to prevent a menu item from appearing. In this example, the collectionView:canPerformAction:forItemAtIndexPath:withSender: method prevents the cut menu from appearing from the edit menu. It enables replication and paste items so that users can insert content.

//Listing 2-6 Selectively disabling actions in the Edit menu (BOOL) collectionView: (UICollectionView *) collectionView canPerformAction: (SEL) action forItemAtIndexPath: (NSIndexPath *) indexPath withSender: (ID) sender only copying and {/ / Support pasting of cells. if ([NSStringFromSelector (action) isEqualToString:@ "copy:"] || [NSStringFromSelector (action) isEqualToString:@ "paste:" return YES]); / / Prevent all other actions. return NO;}

For more information about using clipboard commands, see Text Programming Guide for iOS.

Conversion between layouts

The easiest way to convert between layouts is to use the setCollectionViewLayout:animated: method. However, if you need to control the transition or want it to interact, use the UICollectionViewTransitionLayout object. The
UICollectionViewTransitionLayout class is a special type of layout that can be initialized when a layout object of a collection view is converted to a new layout. Using transformation layout objects, you can make objects follow nonlinear paths, use different timing algorithms, or move on the basis of incoming touch events. The standard class provides a linear transformation for a new layout, but, like the UICollectionViewLayout class, the UICollectionViewTransitionLayout class can be overridden to create any desired effect. In doing so, you need to implement the same method as when you create a custom layout, and allow your implementation to fit into user input, most commonly used in hand gesture recognizers. For more information about creating custom layout objects, see Creating Custom Layouts.
UICollectionViewLayout class provides several methods to track the conversion between UICollectionViewTransitionLayout objects to complete the layout, through the transitionProgress property to track conversion. Once the conversion occurs, your code periodically updates this property to indicate the percentage of the conversion completed. For example, using the UICollectionViewTransitionLayout class and objects such as gesture recognizers, you can use them to transform between layouts, allowing you to create interactive transformations. Similarly, if you implement a custom layout object conversion UICollectionViewTransitionLayout class provides two methods to track the value associated with a layout: updateValue:forAnimatedKey: and valueForAnimatedKey. These methods track special floating point values that can be set and changed during conversion to communicate with layout important information. For example, if you use a kneading gesture to convert between layouts, you can use these methods to tell the layout of the transformation object where the view needs to shift from one another. The steps for
to include UICollectionViewTransitionLayout objects in your app are as follows:

  1. Create an instance of a standard class or your own custom class using the initWithCurrentLayout:nextLayout: method.
  2. Convey the progress of the transformation by periodically modifying the transitionProgress property. Don’t forget to use the set view’s invalidateLayout method to make the layout invalid after you change the progress of the transformation.
  3. Implement the collectionView:transitionLayoutForOldLayout:newLayout: method in the proxy of your collection view and return your transformation layout object.
  4. Optionally modify the layout value using the updateValue:forAnimatedKey: method to indicate the change values associated with the layout object. The stability value in this case is 0.

Official document address
, Designing, Your, Data, Source, and, Delegate