iOS 8: "Go" iOS 8 adaptive Cell

Source: Internet
Author: User

Source Address: http://vit0.com/blog/2014/11/13/ios-8-zi-shi-ying-cell/

This is often the case when using Table view: The contents of the cell in the table view are dynamic, resulting in a cell's height being not known at the time of development, so it is necessary to provide an algorithm for calculating the cell height, each time it is loaded into this cell Calculate the true height of the cell.

Prior to IOS 8

Without using AutoLayout, you need to implement the method of Table view delegate tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat , in which the height of the cell is computed and returned. For example, I have a plain text cell that can display any number of rows, and the code for the cell can be:

123456789      
OverrideFuncTableView(TableView:UITableView,HeightforrowatindexpathIndexpath:Nsindexpath)-CGFloat{ LetContent=Self.Datas[Indexpath.Row]AsString LetPadding:CGFloat=20 LetWidth=TableView.Frame.Size.Width-Padding*2; LetSize=Cgsizemake(Width,CGFloat.Max) LetAttributes=[Nsfontattributename:Uifont(Name:"Helvetica",Size:14)!] LetFrame=content. Boundingrectwithsize (size,  Options: nsstringdrawingoptions. Useslinefragmentorigin, attributes: attributes, context: nil  return framesize. Height+1;                /span>                

The above code is one of the simplest examples, and this example seems to have no problem. However, by looking at the documentation for this delegate method, you can know that each time the reload TableView, the program calculates the height of each cell, and when all the heights have been calculated and the total height of the TableView is determined, To start rendering the view and display it on the screen. This means that a bunch of calculations need to be performed before the table view is displayed, and this is done in the main thread, and if the calculation is too large The program is likely to have a good sense of the card. For example: Table view has thousands of data, or the height of the code to obtain the first image and then calculate the height according to the image, these operations are very slow.

If AutoLayout is used in the cell, it is more cumbersome to calculate the cell height. Interested can see here is an article on how to dynamically calculate height under AutoLayout.

Why not wait to scroll to a cell, and then call the delegate that calculates the cell height? The reason is that TableView needs to get the total height of its content, using this height to determine the size of the scroll bar. Until you UITableViewDelegate add a new API to IOS 7

1
tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat

This method is used to return the estimated height of a cell, and if implemented in the program, TableView does not invoke the method when it is first loaded, heightForRowAtIndexPath but calculates the total height of the tableview with the estimatedHeightForRowAtIndexPath estimated height returned, and then TableView Can be displayed, wait until the cell is visible, and then call to heightForRowAtIndexPath get the correct height of the cell.

By using estimatedHeightForRowAtIndexPath This Delegate method, the performance issues that occur with the first load of table view are resolved. But another problem is that when the cell is not loaded, the height of the cell is calculated, and the code given above simply calculates the height of a nsstring, which requires a lot of code. This calculation is actually necessary, but starting with IOS 8, you may not have to write these annoying computational codes anymore!

The Magic of IOS 8

In IOS 8, the Self size cell provides a mechanism: if the cell has a certain width/height, the AutoLayout automatically calculates the corresponding height/width based on the contents of the cell.

Cell self-adaptation in TableView

There are a few key points to making the cell in the table View Adaptive:

    • The SET AutoLayout constraint must let the cell's contentview know how to extend it automatically. The key point is that the 4 sides of the Contentview have to set the constraints connected to the content, and the content dynamically changes size.
    • The value of the UITableView rowHeight to be set toUITableViewAutomaticDimension
    • As with IOS 7, the method can be implemented to estimatedHeightForRowAtIndexPath increase the first load speed of the table view.
    • Any time the cell intrinsicContentSize changes (such as the width of the table view changes), the table view must be reloaded to update the cell.
Example

Create a new project in Xcode and a Uitableviewcontroller IB in storyboard to create a cell like this:

Figure 1 Cell appearance

There are 3 elements in this cell, where the autolayout constraints of ImageView are:

    • ImageView left to Contentview left 0
    • ImageView top from Contentview top 0
    • The width and height of the ImageView are 80
    • ImageView below Contentview is greater than or equal to 0 (to prevent too little content, the cell height is less than the height of the image)

The AutoLayout constraints of Titlelabel are:

    • Titlelabel left ImageView right 8
    • Titlelabel top and ImageView on the same line.
    • Titlelabel right, right from Contentview, 0.
    • Titlelabel Bottom from description Top 8
    • The height of the Titlelabel is less than or equal to 22 and the priority is 250

The Descriptionlabel constraints are:

    • Descriptionlabel left and Titlelabel left in the same line.
    • Descriptionlabel Top Titlelabel 8
    • Descriptionlabel Bottom Contentview Bottom 0
    • Descriptionlabel right, right from Contentview, 0.

Then load some data into the IB corresponding uitableviewcontroller to show the effect

Figure 2 Adaptive cell

To achieve this effect, I set the AutoLayout, but also set the TableView rowHeight = UITableViewAutomaticDimension , and then this is the case. There is no code to calculate the cell height!! I heightForRowAtIndexPath don't even have to make it, really .... So if already in the development of IOS 8 only application must use AutoLayout, the annoying calculation to AutoLayout go.

Cell self-adaptation in CollectionView

Collection view also allows the cell to adapt to the size of the content, if the Uicollectionview layout is a uicollectionviewflowlayout, you only need to layout.itemSize = ... change layout.estimatedItemSize = ... . As long as layout estimateditemsize,collection view is set, the cell size is determined based on the AutoLayout constraint in the cell.

Principle:

    1. Collection View calculates the estimated contentsize based on the layout's estimateditemsize, with Contentsize collection view starting to show
    2. Collection view in the process of display, the cell that will be displayed is calculated from the size of the fit content according to the constraints of AutoLayout
    3. Layout gets the updated size from Collection view attribute
    4. Layout returns the final size attribute to collection view
    5. Collection uses this final size attribute to display the cell
Summarize

The release of IOS 8 is more convenient for UI development, and many of the code that previously required a lot of computation can now be implemented by dragging and dropping UI controls on IB, but first you will be AutoLayout. If you are lucky to be in the development of IOS 8 only app, you can really delete heightForRowAtIndexPath those heavy computational code! Let AutoLayout do all the work for us.

Reference
    • WWDC Session 226 Whats New in Table and Collection views
    • IOS 8 Tutorial series:auto Sizing Table Cells

iOS 8: "Go" iOS 8 adaptive Cell

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.