ios – 如何使用动态单元格高度和自动布局以编程方式创建非常基本的UITableView?

前端之家收集整理的这篇文章主要介绍了ios – 如何使用动态单元格高度和自动布局以编程方式创建非常基本的UITableView?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
请注意:我知道在类似的行上有很多例子.我正在寻找最基本的解决方案,只需要最少的设置.

我试图自己创造一个,我知道我离开了..

  1. #import "ViewController.h"
  2.  
  3. @interface ViewController () <UITableViewDataSource,UITableViewDelegate>
  4.  
  5. @property(strong,nonatomic) UITableView *tableView;
  6. @property(strong,nonatomic) NSMutableArray *dataArray;
  7. @property (strong,nonatomic) UITableViewCell *customCell;
  8.  
  9. @end
  10.  
  11. @implementation ViewController
  12.  
  13. - (void)viewDidLoad {
  14. [super viewDidLoad];
  15. // Do any additional setup after loading the view,typically from a nib.
  16. self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,self.view.frame.size.width,self.view.frame.size.height) style:UITableViewStylePlain];
  17. [self.tableView setDataSource:self];
  18. [self.tableView setDelegate:self];
  19. [self.tableView setShowsVerticalScrollIndicator:NO];
  20. self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
  21. self.tableView.rowHeight = UITableViewAutomaticDimension;
  22. [self.view addSubview:self.tableView];
  23.  
  24. self.dataArray = [@[@"For the past 33 years,I have looked in the mirror every morning and asked myself: 'If today were the last day of my life,would I want to do what I am about to do today?' And whenever the answer has been 'No' for too many days in a row,I know I need to change something. -Steve Jobs",@"Be a yardstick of quality. Some people aren't used to an environment where excellence is expected. - Steve Jobs",@"Innovation distinguishes between a leader and a follower. -Steve Jobs"] mutableCopy];
  25.  
  26.  
  27. }
  28.  
  29. - (void)didReceiveMemoryWarning {
  30. [super didReceiveMemoryWarning];
  31. // Dispose of any resources that can be recreated.
  32. }
  33.  
  34. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  35.  
  36. return [self.dataArray count];
  37. }
  38.  
  39. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  40. NSString *cellIdentifier = @"CustomCell";
  41. UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
  42.  
  43. if (cell == nil)
  44. {
  45. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
  46. }
  47.  
  48. cell.backgroundColor = [UIColor colorWithRed:249.0/255 green:237.0/255 blue:224.0/255 alpha:1.0];
  49.  
  50. int dataIndex = (int) indexPath.row % [self.dataArray count];
  51. cell.textLabel.text = self.dataArray[dataIndex];
  52. cell.textLabel.numberOfLines = 0;
  53. cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
  54.  
  55. NSDictionary *views = @{@"label":cell.textLabel};
  56. NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[label]|"
  57. options:0
  58. metrics:nil
  59. views:views];
  60. [cell.contentView addConstraints:constraints];
  61.  
  62. constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[label]|"
  63. options: 0
  64. metrics:nil
  65. views:views];
  66. [cell.contentView addConstraints:constraints];
  67.  
  68. return cell;
  69.  
  70. }
  71.  
  72. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  73. // Calculate a height based on a cell
  74. if(!self.customCell) {
  75. self.customCell = [self.tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
  76. }
  77.  
  78. // Configure the cell
  79. int dataIndex = (int) indexPath.row % [self.dataArray count];
  80. self.customCell.textLabel.text = self.dataArray[dataIndex];
  81.  
  82. // auto layout
  83.  
  84. NSDictionary *views = @{@"label":self.customCell.textLabel};
  85. NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[label]|"
  86. options:0
  87. metrics:nil
  88. views:views];
  89. [self.customCell.contentView addConstraints:constraints];
  90.  
  91. constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[label]|"
  92. options: 0
  93. metrics:nil
  94. views:views];
  95. [self.customCell.contentView addConstraints:constraints];
  96.  
  97. // Layout the cell
  98.  
  99. [self.customCell layoutIfNeeded];
  100.  
  101. // Get the height for the cell
  102.  
  103. CGFloat height = [self.customCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
  104.  
  105. // Padding of 1 point (cell separator)
  106. CGFloat separatorHeight = 1;
  107.  
  108. return height + separatorHeight;
  109. }
  110.  
  111. - (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
  112.  
  113. return 140;
  114.  
  115. }
  116.  
  117.  
  118. @end

解决方法

经过大量的例子,我终于明白了什么是错的.它是其中一个缺少线条会扰乱整个代码的东西之一.对我来说是,
  1. cell.bodyLabel.preferredMaxLayoutWidth = tableView.bounds.size.width;

我们需要在heightForRowAtIndexPath方法添加它或者它给出约束错误.

我得到了解决方案,感谢其中一个评论的惊人答案here.虽然在答案中给出的示例代码中,上面的代码行在函数cellForRowAtIndexPath而不是heightForRowAtIndexPath中.但我的代码无法以这种方式运行.

所以,基本代码是,

// RJCell.h

  1. #import <UIKit/UIKit.h>
  2.  
  3. @interface RJTableViewCell : UITableViewCell
  4.  
  5. @property (strong,nonatomic) UILabel *titleLabel;
  6. @property (strong,nonatomic) UILabel *bodyLabel;
  7.  
  8. @end

// RJCell.m

  1. #import "RJTableViewCell.h"
  2.  
  3. @interface RJTableViewCell ()
  4.  
  5. @property (nonatomic,assign) BOOL didSetupConstraints;
  6.  
  7. @end
  8.  
  9. @implementation RJTableViewCell
  10.  
  11. - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
  12. self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
  13. if (self) {
  14. // Initialization code
  15.  
  16. self.titleLabel = [[UILabel alloc] init];
  17. [self.titleLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
  18. [self.titleLabel setLineBreakMode:NSLineBreakByTruncatingTail];
  19. [self.titleLabel setNumberOfLines:1];
  20. [self.titleLabel setTextAlignment:NSTextAlignmentLeft];
  21. [self.titleLabel setTextColor:[UIColor blackColor]];
  22. [self.titleLabel setBackgroundColor:[UIColor clearColor]];
  23. [self.contentView addSubview:self.titleLabel];
  24.  
  25. // Add this label to the button
  26. self.bodyLabel = [[UILabel alloc] init];
  27. [self.bodyLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
  28. [self.bodyLabel setContentCompressionResistancePriority:UILayoutPriorityrequired forAxis:UILayoutConstraintAxisVertical];
  29. [self.bodyLabel setLineBreakMode:NSLineBreakByTruncatingTail];
  30. [self.bodyLabel setNumberOfLines:0];
  31. [self.bodyLabel setTextAlignment:NSTextAlignmentLeft];
  32. [self.bodyLabel setTextColor:[UIColor darkGrayColor]];
  33. [self.bodyLabel setBackgroundColor:[UIColor clearColor]];
  34. [self.contentView addSubview:self.bodyLabel];
  35. }
  36.  
  37. return self;
  38. }
  39.  
  40. - (void)updateConstraints {
  41. [super updateConstraints];
  42.  
  43. if (self.didSetupConstraints) return;
  44.  
  45. // Get the views dictionary
  46. NSDictionary *viewsDictionary =
  47. @{
  48. @"titleLabel" : self.titleLabel,@"bodyLabel" : self.bodyLabel
  49. };
  50.  
  51. NSString *format;
  52. NSArray *constraintsArray;
  53.  
  54. //Create the constraints using the visual language format
  55. format = @"V:|-10-[titleLabel]-10-[bodyLabel]-10-|";
  56. constraintsArray = [NSLayoutConstraint constraintsWithVisualFormat:format options:0 metrics:nil views:viewsDictionary];
  57. [self.contentView addConstraints:constraintsArray];
  58.  
  59. format = @"|-10-[titleLabel]-10-|";
  60. constraintsArray = [NSLayoutConstraint constraintsWithVisualFormat:format options:0 metrics:nil views:viewsDictionary];
  61. [self.contentView addConstraints:constraintsArray];
  62.  
  63. format = @"|-10-[bodyLabel]-10-|";
  64. constraintsArray = [NSLayoutConstraint constraintsWithVisualFormat:format options:0 metrics:nil views:viewsDictionary];
  65. [self.contentView addConstraints:constraintsArray];
  66.  
  67. self.didSetupConstraints = YES;
  68. }
  69.  
  70. @end

// RJTableViewController.h

  1. #import <UIKit/UIKit.h>
  2.  
  3. @interface RJTableViewController : UITableViewController
  4.  
  5. @end

// RJTableViewController.m

  1. #import "RJTableViewController.h"
  2. #import "RJTableViewCell.h"
  3.  
  4. static NSString *CellIdentifier = @"CellIdentifier";
  5.  
  6. @interface RJTableViewController ()
  7.  
  8. @property(strong,nonatomic) NSMutableArray *titleArray;
  9. @property(strong,nonatomic) NSMutableArray *bodyArray;
  10.  
  11. @end
  12.  
  13. @implementation RJTableViewController
  14.  
  15. - (id)initWithStyle:(UITableViewStyle)style
  16. {
  17. self = [super initWithStyle:style];
  18. if (self) {
  19. // Custom initialization
  20. self.title = @"Table View Controller";
  21. }
  22. return self;
  23. }
  24.  
  25. - (void)viewDidLoad
  26. {
  27. [super viewDidLoad];
  28.  
  29. [self.tableView registerClass:[RJTableViewCell class] forCellReuseIdentifier:CellIdentifier];
  30. self.titleArray = [[UIFont familyNames] mutableCopy];
  31. for(int i = 0; i < 100; i++) {
  32. [self.titleArray addObjectsFromArray:[UIFont familyNames]];
  33. }
  34. self.bodyArray = [@[@"Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",@"Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",@"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.",@"Excepteur sint occaecat cupidatat non proident,sunt in culpa qui officia deserunt mollit anim id est laborum."] mutableCopy];
  35. }
  36.  
  37. - (void)contentSizeCategoryChanged:(NSNotification *)notification
  38. {
  39. [self.tableView reloadData];
  40. }
  41.  
  42. #pragma mark - Table view data source
  43.  
  44. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  45. {
  46. // Return the number of sections.
  47. return 1;
  48. }
  49.  
  50. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  51. {
  52. // Return the number of rows in the section.
  53. return [self.titleArray count];
  54. }
  55.  
  56. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  57. {
  58.  
  59. RJTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
  60.  
  61. int dataIndex = (int) indexPath.row % [self.bodyArray count];
  62. cell.titleLabel.text = self.titleArray[indexPath.row];
  63. cell.bodyLabel.text = self.bodyArray[dataIndex];
  64.  
  65. // Make sure the constraints have been added to this cell,since it may have just been created from scratch
  66. [cell setNeedsUpdateConstraints];
  67.  
  68. return cell;
  69. }
  70.  
  71. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  72. {
  73.  
  74. RJTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  75.  
  76. int dataIndex = (int) indexPath.row % [self.bodyArray count];
  77. cell.titleLabel.text = self.titleArray[indexPath.row];
  78. cell.bodyLabel.text = self.bodyArray[dataIndex];
  79.  
  80. cell.bodyLabel.preferredMaxLayoutWidth = tableView.bounds.size.width - (20.0 * 2.0f);
  81.  
  82. [cell setNeedsUpdateConstraints];
  83. [cell updateConstraintsIfNeeded];
  84. [cell.contentView setNeedsLayout];
  85.  
  86. [cell.contentView layoutIfNeeded];
  87.  
  88. CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
  89.  
  90. return height;
  91. }
  92.  
  93. - (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
  94. {
  95. return 200.0f;
  96. }
  97.  
  98. @end

基本上,棘手的部分是在两个地方,首先设置约束.二,实现方法heightForRowAtIndexPath和cellForRowAtIndexPath.

猜你在找的iOS相关文章