Original blog, reproduced please indicate the source
Blog.csdn.net/hello_hwc
Before iOS 8, if you want TableView to automatically resize according to content, you need to dynamically calculate the height of each cell. Tainima Fucked up. After IOS 8, you can automatically adjust the height according to the AutoLayout, the principle is simple.
- DataSource Select let iOS automatically calculate
- In the cell, set the AutoLayout that allows iOS to calculate height, note that it is important to be able to calculate the height of the AutoLayout, which is not the same as the traditional.
Effect
Complete process
Create a new project based on Singleview, then delete the default storyboard Viewcontroller, drag a tableviewcontroller, set as Inital Controller
Drag and drop two Uilabel on prototype cells
Set the cell's reuse identifier to cell
Set a property for two labels
Title
Set tag to 10
Detail
Set tag to 11
Set AutoLayout for two labels
Title
Detail
Notice that the title is placed in the upper-left corner and detail in the lower-left corner. Then add the distance between the two is constant to 1, then the AutoLayout will automatically calculate the height.
Create a new Tableviewcontroller, and speak storyboard on the Tableviewcontroller set to the newly created class
Set the height of the TableView to get automatically
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{ return UITableViewAutomaticDimension;}-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ return UITableViewAutomaticDimension;}
Add an array of stored data and set the data in the initialization
@property (strong , nonatomic ) NSArray * Titlearray; @property (strong , nonatomic ) nsarray * detailarray;
- (void)viewDidLoad { [super viewDidLoad]; self.titleArray = @[@"1",@"2",@"3"]; self.detailArray = @[@"shot",@"Aduahguhauhguhaudghuahguhudhauhg",@"dhuahgudhaughuahdughuahguhauhguhdahudhuahughduahguhadguhaduhguadhughduahguahguhadugh"];}
Next is Tablview common, very good understanding, here not much to repeat
- (Nsinteger) Numberofsectionsintableview: (UITableView*) TableView {return 1;} - (Nsinteger) TableView: (UITableView*) TableView numberofrowsinsection: (Nsinteger) Section {return Self. Titlearray. Count;} -(BOOL) prefersstatusbarhidden{return true;} - (UITableViewCell*) TableView: (UITableView*) TableView Cellforrowatindexpath: (Nsindexpath*) Indexpath {UITableViewCell*cell = [TableView dequeuereusablecellwithidentifier:@"Cell"Forindexpath:indexpath];UILabel* Titlelabel = (UILabel*) [Cell Viewwithtag:Ten];UILabel* Contentlabel = (UILabel*) [Cell Viewwithtag: One]; Titlelabel. Text= Self. Titlearray[Indexpath. Row]; Contentlabel. Text= Self. Detailarray[Indexpath. Row]; Contentlabel. NumberOfLines=0;returnCell;}
Then, we get the effect we want.
IOS 8 TableView automatically adjusts height according to AutoLayout