大佬教程收集整理的这篇文章主要介绍了ios – 如何使用动态单元格高度和自动布局以编程方式创建非常基本的UITableView?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
#import "ViewController.h" @interface ViewController () <UITableViewDatasource,UITableViewDelegate> @property(strong,nonatomiC) UITableView *tableView; @property(strong,nonatomiC) NSMutableArray *dataArray; @property (strong,nonatomiC) UITableViewCell *customcatell; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view,typically from a nib. self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,self.view.frame.size.width,self.view.frame.size.height) style:UITableViewStylePlain]; [self.tableView setDatasource:self]; [self.tableView setDelegate:self]; [self.tableView setShowsVerticalScrollInDicator:NO]; self.tableView.translatesAutoresizingMaskIntoConsTraints = NO; self.tableView.rowHeight = UITableViewAutomaticDimension; [self.view addSubview:self.tableView]; 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]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.dataArray count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowATindexPath:(NSIndexPath *)indexPath { NSString *cellIdentifier = @"Customcatell"; UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reusEIDentifier:cellIdentifier]; } cell.BACkgroundColor = [UIColor colorWithRed:249.0/255 green:237.0/255 blue:224.0/255 alpha:1.0]; int dataIndex = (int) indexPath.row % [self.dataArray count]; cell.textLabel.text = self.dataArraY[dataIndex]; cell.textLabel.numberOfLines = 0; cell.textLabel.lineBreakmode = NSLineBreakByWordWrapping; NSDictionary *views = @{@"label":cell.textLabel}; NSArray *consTraints = [NSLayoutConsTraint consTraintsWithVisualFormat:@"H:|[label]|" options:0 metrics:nil views:views]; [cell.contentView addConsTraints:consTraints]; consTraints = [NSLayoutConsTraint consTraintsWithVisualFormat:@"V:|[label]|" options: 0 metrics:nil views:views]; [cell.contentView addConsTraints:consTraints]; return cell; } - (CGFloat)tableView:(UITableView *)tableView heightForRowATindexPath:(NSIndexPath *)indexPath { // Calculate a height based on a cell if(!self.customcatell) { self.customcatell = [self.tableView dequeueReusableCellWithIdentifier:@"Customcatell"]; } // Configure the cell int dataIndex = (int) indexPath.row % [self.dataArray count]; self.customcatell.textLabel.text = self.dataArraY[dataIndex]; // auto layout NSDictionary *views = @{@"label":self.customcatell.textLabel}; NSArray *consTraints = [NSLayoutConsTraint consTraintsWithVisualFormat:@"H:|[label]|" options:0 metrics:nil views:views]; [self.customcatell.contentView addConsTraints:consTraints]; consTraints = [NSLayoutConsTraint consTraintsWithVisualFormat:@"V:|[label]|" options: 0 metrics:nil views:views]; [self.customcatell.contentView addConsTraints:consTraints]; // Layout the cell [self.customcatell layoutIfNeeded]; // Get the height for the cell CGFloat height = [self.customcatell.contentView systemLayoutSizeFitTingSize:UILayoutFitTingCompressedSize].height; // Padding of 1 point (cell separator) CGFloat separatorHeight = 1; return height + separatorHeight; } - (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowATindexPath:(NSIndexPath *)indexPath { return 140; } @end
cell.bodyLabel.preferredMaxLayoutWidth = tableView.bounds.size.width;
我们需要在heightForRowATindexPath方法中添加它或者它给出约束错误.
我得到了解决方案,感谢其中一个评论的惊人答案here.虽然在答案中给出的示例代码中,上面的代码行在函数cellForRowATindexPath而不是heightForRowATindexPath中.但我的代码无法以这种方式运行.
所以,基本代码是,
// RJCell.h
#import <UIKit/UIKit.h> @interface RJTableViewCell : UITableViewCell @property (strong,nonatomiC) UILabel *titleLabel; @property (strong,nonatomiC) UILabel *bodyLabel; @end
// RJCell.m
#import "RJTableViewCell.h" @interface RJTableViewCell () @property (nonatomic,assign) BOOL didSetupConsTraints; @end @implementation RJTableViewCell - (id)initWithStyle:(UITableViewCellStylE)style reusEIDentifier:(NSString *)reusEIDentifier { self = [super initWithStyle:style reusEIDentifier:reusEIDentifier]; if (self) { // Initialization code self.titleLabel = [[UILabel alloc] init]; [self.titleLabel setTranslatesAutoresizingMaskIntoConsTraints:NO]; [self.titleLabel setLineBreakmode:NSLineBreakByTruncaTingTail]; [self.titleLabel setnumberOfLines:1]; [self.titleLabel setTextAlignment:NSTextAlignmentLeft]; [self.titleLabel setTextColor:[UIColor blackColor]]; [self.titleLabel setBACkgroundColor:[UIColor clearColor]]; [self.contentView addSubview:self.titleLabel]; // Add this label to the button self.bodyLabel = [[UILabel alloc] init]; [self.bodyLabel setTranslatesAutoresizingMaskIntoConsTraints:NO]; [self.bodyLabel setContentCompressionResistancePriority:UILayoutPriorityrequired forAxis:UILayoutConsTraintAxisVertical]; [self.bodyLabel setLineBreakmode:NSLineBreakByTruncaTingTail]; [self.bodyLabel setnumberOfLines:0]; [self.bodyLabel setTextAlignment:NSTextAlignmentLeft]; [self.bodyLabel setTextColor:[UIColor darkGrayColor]]; [self.bodyLabel setBACkgroundColor:[UIColor clearColor]]; [self.contentView addSubview:self.bodyLabel]; } return self; } - (void)updateConsTraints { [super updateConsTraints]; if (self.didSetupConsTraints) return; // Get the views Dictionary NSDictionary *viewsDictionary = @{ @"titleLabel" : self.titleLabel,@"bodyLabel" : self.bodyLabel }; NSString *format; NSArray *consTraintsArray; //Create the consTraints using the visual language format format = @"V:|-10-[titleLabel]-10-[bodyLabel]-10-|"; consTraintsArray = [NSLayoutConsTraint consTraintsWithVisualFormat:format options:0 metrics:nil views:viewsDictionary]; [self.contentView addConsTraints:consTraintsArray]; format = @"|-10-[titleLabel]-10-|"; consTraintsArray = [NSLayoutConsTraint consTraintsWithVisualFormat:format options:0 metrics:nil views:viewsDictionary]; [self.contentView addConsTraints:consTraintsArray]; format = @"|-10-[bodyLabel]-10-|"; consTraintsArray = [NSLayoutConsTraint consTraintsWithVisualFormat:format options:0 metrics:nil views:viewsDictionary]; [self.contentView addConsTraints:consTraintsArray]; self.didSetupConsTraints = YES; } @end
// RJTableViewController.h
#import <UIKit/UIKit.h> @interface RJTableViewController : UITableViewController @end
// RJTableViewController.m
#import "RJTableViewController.h" #import "RJTableViewCell.h" static NSString *CellIdentifier = @"CellIdentifier"; @interface RJTableViewController () @property(strong,nonatomiC) NSMutableArray *titleArray; @property(strong,nonatomiC) NSMutableArray *bodyArray; @end @implementation RJTableViewController - (id)initWithStyle:(UITableViewStylE)style { self = [super initWithStyle:style]; if (self) { // Custom initialization self.title = @"Table View Controller"; } return self; } - (void)viewDidLoad { [super viewDidLoad]; [self.tableView registerClass:[RJTableViewCell class] forCellReusEIDentifier:CellIdentifier]; self.titleArray = [[UIFont familyNames] mutableCopy]; for(int i = 0; i < 100; i++) { [self.titleArray addObjectsFromArray:[UIFont familyNames]]; } 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]; } - (void)contentSizeCategoryChanged:(Nsnotification *)notification { [self.tableView reloadData]; } #pragma mark - Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. return [self.titleArray count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowATindexPath:(NSIndexPath *)indexPath { RJTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; int dataIndex = (int) indexPath.row % [self.bodyArray count]; cell.titleLabel.text = self.titleArraY[indexPath.row]; cell.bodyLabel.text = self.bodyArraY[dataIndex]; // Make sure the consTraints have been added to this cell,since it may have just been created from scratch [cell setNeedsupdateConsTraints]; return cell; } - (CGFloat)tableView:(UITableView *)tableView heightForRowATindexPath:(NSIndexPath *)indexPath { RJTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; int dataIndex = (int) indexPath.row % [self.bodyArray count]; cell.titleLabel.text = self.titleArraY[indexPath.row]; cell.bodyLabel.text = self.bodyArraY[dataIndex]; cell.bodyLabel.preferredMaxLayoutWidth = tableView.bounds.size.width - (20.0 * 2.0f); [cell setNeedsupdateConsTraints]; [cell updateConsTraintsIfNeeded]; [cell.contentView setNeedsLayout]; [cell.contentView layoutIfNeeded]; CGFloat height = [cell.contentView systemLayoutSizeFitTingSize:UILayoutFitTingCompressedSize].height; return height; } - (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowATindexPath:(NSIndexPath *)indexPath { return 200.0f; } @end
基本上,棘手的部分是在两个地方,首先设置约束.二,实现方法heightForRowATindexPath和cellForRowATindexPath.
以上是大佬教程为你收集整理的ios – 如何使用动态单元格高度和自动布局以编程方式创建非常基本的UITableView?全部内容,希望文章能够帮你解决ios – 如何使用动态单元格高度和自动布局以编程方式创建非常基本的UITableView?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。