Turn Tableviewcell with AutoLayout Xib to achieve dynamic heights

Source: Internet
Author: User

Create a Xib file

First, the cell layout, adjust to the satisfactory position and width, and then start to do AutoLayout settings.

There are two ways to operate the AutoLayout, one is to select the target, use the lower right corner of the toolbar, and the other is to use right-click to drag the target and select the limit in the popup menu. When the target is relatively small, you can open the menu on the left side, as you can do with drag and drop operations. Individuals feel that the latter is more convenient.

Before you begin, let's start by introducing the basic tools you'll use.

The first button is related to alignment, which is the uniform constraint that controls multiple elements (lable, button, and so on). For example, we need to leave the title and content on the left, select the title and content elements, select leading edges set to 5.

The second button is a restriction on the position of the element, and look directly at the graph:

The right side can see a list of the current selection element constraints:


Here are two parameters, "content hugging priority" and "content Compression resistance priority", feel not very good understanding, stack explosion found an explanation, speak very good: Cocoa Autolayout:content hugging vs content compression resistance priority

Sometimes you want the spacing of an element to be a dynamic value, such as at least 10pt from the right side (i.e. >=10pt), then you can click on the right button (gear) to enter detailed settings:

The third button is a tool for clearing restrictions, updating the view size according to limits. Personal more commonly used is to clear the restrictions, and sometimes set the wrong is very troublesome, direct removal of the re-on the line.

These are some of the limitations that are commonly used. I think it is more convenient and intuitive to use right-click Drag-and-drop popup menu, because the menu will dynamically display the available items according to the drag content for our selection, menu

That's roughly what this is about.

I'll talk about my own usage. On the whole, from top to bottom, constraints are constrained from left to right. In this case, it is the order of the posts, such as the title, content, and so on.

    1. Sets the top and left distance of the caption, as well as the width (to prevent out of bounds).

    2. Sets the top (distance title) and left distance of the content, as well as the width. Sets the maximum number of rows.

    3. Sets the top and left distance of the poster, as well as the height.

    4. Sets the distance between the top and left of the posting time, and the distance to the right (prevents the content from being too long).

    5. Key steps, set the poster distance from the bottom, if you do not set this parameter, then the following code calculates the cell height will always be 0.

Try again, and if there is an error or a lack of restrictions, Xcode will be prompted. It usually has to fix the error, but it gives the automatic correction suggestions are sometimes not what we want (right), want to clearly add.

Code section

Using the cell created by xib, how do you use it in the original project code? Look at the code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21st

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

static NSString *cellidentifier = @ "Cellidentifier";

-(void) viewdidload

{

Registering a cell in the TableView for reuse

[Self.tableview registernib:[uinib nibwithnibname:@ "Bbspostcontentcell" Bundle:nil] ForCellReuseIdentifier: Cellidentifier];

//...

}

Key method, get the multiplexed cell post-simulation assignment, and then get the cell height

-(CGFloat) TableView: (UITableView *) TableView Heightforrowatindexpath: (Nsindexpath *) Indexpath

{

Bbspostcontentcell *cell = [TableView dequeuereusablecellwithidentifier:cellidentifier];

Nsdictionary *datasourceitem = [Self.datasource objectAtIndex:indexPath.row];

Cell.titleLabel.text = [Datasourceitem valueforkey:@ "title"];

Cell.contentLabel.text = [Datasourceitem valueforkey:@ "Body"];

[Cell setneedsupdateconstraints];

[Cell updateconstraintsifneeded];

CGFloat height = [Cell.contentview systemlayoutsizefittingsize:uilayoutfittingcompressedsize].height;

return height;

}

In Cellforrowatindexpath, it's OK to do the assignment by the usual method.

-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath

{

Bbspostcontentcell *cell = [TableView dequeuereusablecellwithidentifier:cellidentifier];

Nsdictionary *dic = Datasource[indexpath.row];

Cell.titleLabel.text = dic[@ "title"];

Cell.contentLabel.text = dic[@ "Body"];

return cell;

}

2014.1.2: There are some performance problems with this part of the code during testing (the entire table view will be stuck in the update) and I'll make it up later.

I'm using instruments analysis to find that calling Dequeuereusablecellwithidentifier in Heightforrowatindexpath consumes a lot of CPU resources, So I tried not to use the Registernib method to register the Multiplexed cell, but to do it manually in the code, like this:

1

2

3

4

5

6

7

Bbspostcontentcell *cell = [TableView dequeuereusablecellwithidentifier:cellidentifier];

if (cell = = nil) {

cell = [[NSBundle mainbundle] loadnibnamed:@ "Bbspostcontentcell" owner:self options:null][0];

NSLog (@ "cell loadnibnamed");

} else {

NSLog (@ "cell dequeuereusablecellwithidentifier");

}

At this point I found that the cell call Dequeuereusablecellwithidentifier method here always returns nil, so each time it is loaded from the xib, which consumes a lot of resources. The cause of the problem I'm not sure, my workaround now is to generate a single cell for calculating the height in the Heightforrowatindexpath method.

Second, when [TableView Reloaddata] and [TableView insertrowsatindexpaths], the bottom layer would recalculate all the rows, which would take a lot of time, so I tried to cache the row heights and temporarily solved the problem.

About compatibility issues

As AutoLayout can only be used in iOS6.0 or above, and according to the Friends of the league statistics, the current user of 6.0 or less is about 8% (2013.12). Now there are two ways to solve it:

    1. Brother don't care, give up these users! (Good domineering =.) =) Change the deployment version of the project to more than 6.0.

    2. Cough... Cough... Well, the user still needs to support ..... Well, let's talk about how this is compatible.

The idea is very simple, we tell xcode,6.0 the above version uses AutoLayout, the following old version does not use this to be possible.

Select "Interface Builder document", "Build for", "IOS 6.0 and later" in the original Xib file inspector, and tell Xcode that this xib is compiled at more than 6.0 devices.

Copy a copy of the Xib file, named "Xxx_ios5.xib", and select "Project Deployment target" in inspector, i.e. use the project deployment target version (that is, minimum version 5.0) and cancel AutoLayout "option.

Load different xib files in your code according to the system version:

1

2

3

4

5

6

7

8

9

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO (v) \

([[[uidevice  currentdevice] systemversion] compare:v options:nsnumericsearch] !=  nsorderedascending)

 

#define is_support_autolayout   System_version_greater_than_or_ Equal_to (@ "6.0")

 

-  (void) viewdidload

{

if  (!is_support_autolayout)  {

    //for IOS 5.x

    [self.tableView  registernib:[uinib nibwithnibname:@ "Bbspostcontentcell_ios5"  bundle:nil] forcellreuseidentifier : Cellidentifier];

} else {

    [self.tableView registerNib:[UINib  nibwithnibname:@ "Bbspostcontentcell"  bundle:nil] forcellreuseidentifier:cellidentifier];

}

}

Finally, don't forget to differentiate the code when height is calculated:

1

2

3

4

5

6

7

8

9

10

11

12

-(CGFloat) TableView: (UITableView *) TableView Heightforrowatindexpath: (Nsindexpath *) Indexpath

{

if (is_support_autolayout) {

AutoLayout Part code, IBID.

//.....

return height;

} else {

For IOS 5.x

For the sake of simplicity, it is possible to use a fixed value directly, but if you want to manually calculate the dynamic height for the iOS5 user.

return 81;

}

}

It's done!

Go to Tableviewcell using AutoLayout xib to achieve dynamic heights

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.