In iOS 8, Tableview automatically adjusts the height and iostableview height based on AutoLayout.
Original Blog, reprinted, please indicate the source
Blog.csdn.net/hello_hwc
Before iOS 8, If you want Tableview to automatically resize according to the content, you need to calculate the height of each cell dynamically. Tanima is a zombie. After iOS 8, you can automatically adjust the height based on AutoLayout. The principle is very simple.
- In DataSource, select enable iOS to calculate automatically
- In Cell, the setting allows iOS to calculate the AutoLayout height. Note that AutoLayout must be calculated here, which is different from the traditional one.
Effect
Complete process
Create a singleview-based project, delete the ViewController of the default Storyboard, drag a TableviewController, and set it to incomcontroller.
Drag two UILabel objects to Prototype Cells.
Set the reuse identifier of the cell to cell.
Set attributes for two labels
Title
Set tag to 10
Detail
Set tag to 11
Set AutoLayout for two labels
Title
Detail
Note: place the title in the upper left corner and the Detail in the lower left corner. Then, if the distance between the two is constant to 1, AutoLayout automatically calculates the height.
Create a new TableviewController and set tableviewController on storyboard as the new class.
Set the height of Tableview to automatically retrieve
-(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 data in 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"];}
The next step is the commonly used Tablview, which is easy to understand. I will not repeat it here
- (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:10]; UILabel * contentLabel = (UILabel *)[cell viewWithTag:11]; titleLabel.text = self.titleArray[indexPath.row]; contentLabel.text = self.detailArray[indexPath.row]; contentLabel.numberOfLines = 0; return cell;}
Then we get the desired effect.