我使用Interface Builder创建了一个自定义TableView单元。这是什么样子:具有多行UILabel的自定义Tableview单元需要动态高度
对于说明标签,我需要到自动换行,所以我把它设置为这样:
在我SettingsPageViewController,我有下面的表视图方法被覆盖:
@implementation SBSettingsViewController
{
NSArray *settingHeaders;
NSArray *settingDescriptions;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self setupLeftMenuButton];
// Do any additional setup after loading the view from its nib.
settingHeaders = [NSArray arrayWithObjects:@"Label Header 1",@"Label Header 2",nil];
settingDescriptions = [NSArray arrayWithObjects:@"Two line description Two line description Two line description ",@"One Line Description",nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [settingHeaders count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *simpleTableIdentifier = @"SettingsTableCell";
SettingsTableViewCell *cell = (SettingsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SettingsTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.settingsHeaderLabel.text = [settingHeaders objectAtIndex:indexPath.row];
cell.settingsDescriptionLabel.text = [settingDescriptions objectAtIndex:indexPath.row];
cell.settingsDescriptionLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.settingsDescriptionLabel.numberOfLines = 0;
CGRect appFrame=[[UIScreen mainScreen] bounds];
cell.settingsDescriptionLabel.preferredMaxLayoutWidth = appFrame.size.width - 15;
[cell.settingsDescriptionLabel sizeToFit];
[cell.settingsDescriptionLabel setNeedsDisplay];
[cell layoutIfNeeded];
return cell;
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
[tableView setSeparatorInset:UIEdgeInsetsZero];
}
if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
[tableView setLayoutMargins:UIEdgeInsetsZero];
}
if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 85;
}
下面是结果页面的样子:
正如你可以看到,为第1的tableview细胞的说明标签不换行。它只是切断。 如何让它包裹?
另外,我想要动态调整Tableview单元格高度。我试图改变heightForRowAtIndexPath:是UITableViewAutomaticDimension但只是使它看起来超级怪异这样:
我如何调整与1号线的说明标签,该行的实现代码如下高度稍短?
感谢您的帮助!
可能[sizeToFit()的副本返回错误的高度 - 需要在heightForRow中查找单元格宽度(http://stackoverflow.com/questions/34731721/sizetofit-returns-wrong-height-need-to-find-cell-width-in -heightforrow) – SwiftArchitect
检查此链接 - http://stackoverflow.com/questions/3472478 3 /如何创建动态视图在迅速/ 34726428#34726428 –