AutoLayout Five [uitableview dynamic height]

Source: Internet
Author: User

this article reprinted to http://grayluo.github.io//WeiFocusIo/autolayout/2015/02/01/autolayout5/

We often encounter the height of UITableViewCell to follow the content and adjust, before we introduce AutoLayout, we use the following method to calculate the label height, and then return the height of the calculation in Heightforrowatindexpath, this practice, Really very limited is not very good, if Uilabel used Coretext or Uikit for rich text different font layout, it is no way, I also have to segment to calculate, in short, all kinds of trouble.

- (cgsizesizewithfont:  (uifont *) font constrainedtosize: (cgsize) linebreakmode: (nslinebreakmode) linebreakmode ns_deprecated_ios (2 _07_0 "use- BoundingRectWithSize:options:attributes:context: "); //nstextalignment is not needed to determine size         

This series of articles we are talking about is AutoLayout, that iOS6 the introduction of AutoLayout, has the situation changed? Of course! And AutoLayout is constantly being optimized for developers to lay out in the process of updating iOS. To tell the truth, like many developers, I am not particularly fond of AutoLayout, there are some uncontrolled factors, the layout is not fully grasp in their own hands, need to rely on the system to adjust according to constraints, which makes conservative developers very insecure. No nonsense, we still get into the chase.

We have a realistic need to discuss, for example, we need to build a page, the above section shows the basic information of our reservation maintenance, the following section shows the list of coupons currently provided by the store, the simplest way is to directly use two kinds of uitableviewcell, The following section of the UITableViewCell to be simple, highly fixed, and the above section of the UITableViewCell content has a lot of uncertain content, such as the user to schedule the maintenance of the selected items, the name and address of the store, these uilabel height are uncertain, So the height of the upper part of the UITableViewCell needs to be adjusted dynamically, this is a typical example, let's take a look at how to solve.

First, establish a reasonable restraint

Let's start by creating a custom Cell:appointmentedinfocell (create Xib). Then set the reasonable constraints, what is the reasonable constraints, on the one hand we need to set the correct constraints as described above, on the other hand I mean the main control compression resistance and hugging constraints, in the IB as:

We know that in AutoLayout, our Uilabel,uibutton and other controls have built-in size (intrinsic content size), which means that the size of the control is automatically adjusted according to the content. You can compare the size of these controls to the ScrollView bounds and contentsize, which is a bit similar, except Uilabel, UIButton These controls do not scroll through the contents of the bounds without equal contentsize, as ScrollView does. In order to use the built-in size of the Uilabel, we want to maintain that the vertical priority of the compression resistance and hugging constraints is not overwritten by a higher priority, such as changing the priority of the Uilabel built-in size ( Priority), and set the Uilabel's height constraint precedence over the built-in size, the built-in size naturally does not work, and will be based on high priority.

  • Here is an official description of the intrinsic content size: Custom views typically has content that they display of which the layout system is Unaw Is. Overriding this method allows a custom view to communicate to the layout system "what size it would" like "based on its Content. This intrinsic size must is independent of the content frame, because there ' s no to dynamically communicate a changed Width to the layout system based on a changed height, for example. Editing Auto Layout Constraints

On the one hand, we ensured that the controls in the Appointmentedinfocell are now all Uilabel, with the highest vertical priority of 1000 for the built-in size. Light This is not enough, we also want to ensure that the built-in size of the edge following the built-in size changes together, so as to ensure that our built-in size can work, in short, is to require contentview in the child control to establish and superview constraints, we first set up the first Uilabel (name, Phone) with the Superview top spacing constraint, and then down to establish the constraint between the control recommended spacing, left the same column control to establish the left alignment constraints, the right peer content to establish the top alignment constraints, vertical spacing constraints, the bottom of the "Appointment result label" establishment and Superview The spacing constraint for the bottom.

Special reminder: With the contentview of the four-sided spacing constraint is very important, with 4 and Contentview edge constraints, to ensure that the size of Contentview follow its subviews changes.

These are the establishment of reasonable constraints, here casually to remind, Uilabel in the IB layout size if the content calculated inconsistent with a warning, such as Uilabel length of 200, the current content is 2 14th number of length, then Uilabel will have a warning, For this kind of warning, you need to resist your obsessive-compulsive disorder.

Second, calculate the row height

This step in iOS7 and iOS8 above is different, we first look at the latest iOS8.

1, IOS8:

From IOS8 began to introduce the uitableviewcell of the height of the adaptive function, before iOS8 to achieve a cumbersome function, iOS8 will not need to do their own, later we will look at iOS7 below how to do.

//打开tableview的高度估算功能_iTableView.rowHeight = UITableViewAutomaticDimension;_iTableView.estimatedRowHeight = 70.0;

Estimatedrowheight must be set to greater than 0, in order to over-smooth the picture, to ensure that the uitableview height changes do not lead to a wide range of uitableview scrolling and affect the user visual experience, we use an estimated average, which is called pre-valuation. Estimatedrowheight is not the final row height, when a cell needs to be displayed, the actual row height is calculated accurately, the width of the contentview is UITableView width minus the section Index, The width of the accessoryview, the height of the Contentview will automatically be calculated according to the constraints of its sub-view, when the exact value is calculated, Estimatedrowheight, TableView contentsize,bounds, These will follow the update.

Estimatedrowheight each row uses this value for the row's pre-estimate, which in turn initially estimates the contentsize of the UITableView. If the UITableView each row varies greatly and the row height varies greatly, then we can use the following method to set different estimates for each row. In other words, there are universal values and personality values.

- (void)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath;

OK, the pre-valuation is just an episode, we look at the exact value, after iOS8, we simply activate the pre-estimate and return to uitableviewautomaticdimension in Heightforrowatindexpath.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ if (IS_IOS8_OR_ABOVE) { return UITableViewAutomaticDimension; }}

2, IOS7:

UITableViewCell's Contentview height adaptive is iOS8 added, iOS7 can only calculate their own, so we look at the iOS7 how to deal with.

NIB Registration, there are many ways to get custom UITableView instances, here's aUinib*Cellnib=[UinibNibwithnibname:@ "Appointmentedinfocell"Bundle:Nil];[Self.TableViewRegisternib:CellnibForcellreuseidentifier:@ "Appointmentedinfocell"];To create a basic cell instance, we need to use the following Cellforrowatindexpath and Heightforrowatindexpath, because the UITableView loading process is to calculate all the row heights, and then render each row, That is, Heightforrowatindexpath is called first, so the Basecell here is an off-screen control, used to aid the calculation of height, and the latter can be directly used for each line of content updates, each type of cell only need one, So our off-screen memory is not wasted._basecell=[CellnibInstantiatewithowner:NilOptions:Nil][0];Update cell content-(void)Configurecell:(Appointmentedinfocell*)CellAtindexpath:(Nsindexpath*)Indexpath{To update Contentview child controls}//-(UITableViewCell*)TableView:(UITableView*)TableViewCellforrowatindexpath:(Nsindexpath*)Indexpath{Appointmentedinfocell*Cell=[TableViewDequeuereusablecellwithidentifier:@ "Appointmentedinfocell"Forindexpath:Indexpath];[SelfConfigurecell:CellAtindexpath:Indexpath];ReturnCell;}//-(CGFloat)TableView:(UITableView*)TableViewHeightforrowatindexpath:(Nsindexpath*)Indexpath{[self configurecell:_basecell  Atindexpath:indexpath[_basecell layoutsubviewscgfloat height = [_basecellcontentview systemlayoutsizefittingsize: Uilayoutfittingcompressedsize. heightreturn height + 1; Because of the split line, the height of the contentview is smaller than row one pixel.                /span>                

When writing this article, in order to be able to provide a comprehensive solution is not too limited, so as not to mislead readers, I read a lot of articles, the basic idea is the above, the difference is in the details of the processing, such as the UITableViewCell of the instantiation there are many ways such as:

StaticNSString*Cellidentifier=@ "Appointmentedinfocell";Appointmentedinfocell*Cell=(Appointmentedinfocell*)[TableViewDequeuereusablecellwithidentifier:Cellidentifier; if  (cell == nil) {nsarray *cellteam = [[nsbundle mainbundle]  Loadnibnamed:cellidentifier owner: self options:nilcell = [cellteam objectatindex< Span class= "p" >:0];}         

Also some netizens skillfully used dispatch_once:

static  Appointmentedinfocell *basecell; Static dispatch_once_t oncetoken; Dispatch_once (&oncetoken^ {basecell = [[ Appointmentedinfocell alloc] initwithstyle:< span class= "n" >uitableviewcellstyledefault reuseidentifier: Mytableviewcellidentifier;                

OK, here, we basically mastered the AutoLayout of the UITableViewCell dynamic height of the processing, the key point is the use of systemlayoutsizefittingsize, Hopefully this article will help you to better understand AutoLayout and UITableView's new layout processing in iOS8.

Reference:
This article is mainly used for a summary of knowledge, the process may be referenced to other places of text or code, if there is infringement please contact me, in this writing process reference to the author of the article to express my thanks!

  • http://blog.jldagon.me/blog/2013/12/07/auto-layout-and-uitableview-cells/
  • Corresponding Demo
  • Http://useyourloaf.com/blog/2014/02/14/table-view-cells-with-varying-row-heights.html
  • Corresponding Demo
  • http://www.raizlabs.com/dev/2014/02/leveraging-auto-layout-for-dynamic-cell-heights/
  • Corresponding Demo
  • Http://stackoverflow.com/questions/18746929/using-auto-layout-in-uitableview-for-dynamic-cell-layouts-variable-row-heights
  • Chinese Translation version
  • Purelayout
  • Http://www.raywenderlich.com/73602/dynamic-table-view-cell-height-auto-layout
  • Https://github.com/Alex311/TableCellWithAutoLayout
  • http://www.ifun.cc/blog/2014/02/21/dong-tai-ji-suan-uitableviewcellgao-du-xiang-jie/
  • Http://blog.amyworrall.com/post/66085151655/using-auto-layout-to-calculate-table-cell-height
  • http://www.macspotsblog.com/dynamic-uitableview-cell-heights-programmatically/
  • Http://www.cnblogs.com/gatsbywang/p/4216706.html

AutoLayout Five [uitableview dynamic height]

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.