IOS 8 Adaptive Cell

Source: Internet
Author: User

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 TableView (Tableview:uitableview, Heightforrowatindexpath indexpath for table View delegate: Nsindexpath)-CGFloat method, which calculates and returns the height of the cell in this method. For example, I have a plain text cell that can display any number of rows, and the code for the cell can be:

Override func tableview (Tableview: uitableview, heightforrowatindexpath indexpath:  nsindexpath)  -> CGFloat {    let content =  self.datas[indexpath.row] as string    let padding: cgfloat =  20    let width = tableview.frame.size.width - padding  * 2;    let size = cgsizemake (Width, CGFloat.max)      let attributes = [nsfontattributename: uifont (name:  "Helvetica",  SIZE: 14)!]     let frame = content.boundingrectwithsize (size,         options: NSStringDrawingOptions.UsesLineFragmentOrigin,         attributes: attributes,        context:  nil)     return frame.size.height+1;} 

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. The new API was added to IOS 7 uitableviewdelegate:

TableView (Tableview:uitableview, Estimatedheightforrowatindexpath indexpath:nsindexpath), cgfloat

This method is used to return the estimated height of a cell, and if this method is implemented in the program, TableView will not invoke the Heightforrowatindexpath method when it is first loaded, but The estimated height returned by the Estimatedheightforrowatindexpath calculates the total height of the TableView, and then the TableView can be displayed until the cell is visible. Then call Heightforrowatindexpath to get the correct height of the cell.

By using Estimatedheightforrowatindexpath, this Delegate method resolves the performance issues that occur with the first load of table view. 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:

1. 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.

2.the value of UITableView rowHeight is set to Uitableviewautomaticdimension

3. As with IOS 7, you can implement the Estimatedheightforrowatindexpath method to increase the first load speed of a table view.

4. any time the intrinsiccontentsize of the cell changes (such as the width of the table view has changed), 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:

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

To achieve this effect, I have 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 don't even have to Heightforrowatindexpath, it's 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

The 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 to 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 estimateditemsize of layout, 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 adaptive content according to the constraints of the 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're lucky to be in the development of IOS 8 only apps, you can really remove the heavy computational code from Heightforrowatindexpath! Let AutoLayout do all the work for us.

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.