Luk*_*uke 19 objective-c uitableview ios
所以,似乎heightForRowAtIndexPath之前被称为cellForRowAtIndexPath.我目前正在使用cellForRowAtIndexPath计算每个单元格的高度(它们是可变高度,使用其中UILabel包含不同数量的文本.
如果在计算它的方法之前调用设置高度的方法,我对如何正确设置单元格的高度感到困惑.
我已经创建了一个类别NSString,另一个UILabel,它们共同构成UILabel了合适的大小.问题是UITableViewCell包含这些标签的实例没有调整大小,因此标签悬挂在每个标签的末尾,与下面的标签重叠.
我知道我需要做的是让单元格的高度等于标签的高度,再加上一些额外的边距空间,但是我很困惑如何在计算标签高度之前设置高度.我可以在不使用的情况下设置身高heightForRowAtIndexPath吗?或者如果没有,我可以在其他地方计算出细胞的高度吗?我目前正在indexPath.row尝试实现这一目标,所以事先做这件事会很棘手.这是代码我的cellForRowAtIndexPath:
的cellForRowAtIndexPath
- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
FQCustomCell *_customCell = [tableView dequeueReusableCellWithIdentifier: @"CustomCell"];
if (_customCell == nil) {
_customCell = [[FQCustomCell alloc] initWithStyle: UITableViewCellStyleValue1 reuseIdentifier: @"CustomCell"];
}
_customCell.myLabel.text = [[_loadedNames objectAtIndex: indexPath.row] name];
_customCell.myLabel.font = [UIFont fontWithName: @"FontA" size: 15.0f];
UIView *backView = [[UIView alloc] initWithFrame: CGRectZero];
backView.backgroundColor = [UIColor clearColor];
_customCell.backgroundView = backView;
_customCell.myLabel.frame = CGRectMake(5, 5, 265, 65);
[_customCell.myLabel sizeToFitMultipleLines];
return _customCell;
}
Run Code Online (Sandbox Code Playgroud)
JP *_*sek 15
您需要计算单元格的高度heightForRowAtIndexPath,例如
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *theText=[[_loadedNames objectAtIndex: indexPath.row] name];
CGSize labelSize = [theText sizeWithFont:[UIFont fontWithName: @"FontA" size: 15.0f] constrainedToSize:kLabelFrameMaxSize];
return kHeightWithoutLabel+labelSize.height;
}
Run Code Online (Sandbox Code Playgroud)
您可以通过设置为标签大小设置一些约束 kLabelFrameMaxSize
#define kLabelFrameMaxSize CGSizeMake(265.0, 200.0)
Run Code Online (Sandbox Code Playgroud)
然后通过添加具有可变标签高度的恒定高度来返回高度.
此外,为了保持一致,您应该使用相同的方法来设置框架cellForRowAtIndexPath而不是使用sizeToFitMultipleLines
- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
FQCustomCell *_customCell = [tableView dequeueReusableCellWithIdentifier: @"CustomCell"];
if (_customCell == nil) {
_customCell = [[FQCustomCell alloc] initWithStyle: UITableViewCellStyleValue1 reuseIdentifier: @"CustomCell"];
}
_customCell.myLabel.text = [[_loadedNames objectAtIndex: indexPath.row] name];
_customCell.myLabel.font = [UIFont fontWithName: @"FontA" size: 15.0f];
UIView *backView = [[UIView alloc] initWithFrame: CGRectZero];
backView.backgroundColor = [UIColor clearColor];
_customCell.backgroundView = backView;
CGSize labelSize = [_customCell.myLabel.text sizeWithFont:_customCell.myLabel.font constrainedToSize:kLabelFrameMaxSize];
_customCell.myLabel.frame = CGRectMake(5, 5, labelSize.width, labelSize.height);
return _customCell;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18385 次 |
| 最近记录: |