我使用单独的UILabel类定义了Cell中我的Label的边距:
- (void)drawTextInRect:(CGRect)rect {
UIEdgeInsets insets = {5, 10,5, 10};
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}
使用以下代码,我从单元格中定义高度:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if (!self.customCell) {
self.customCell = [self.chatTableView dequeueReusableCellWithIdentifier:@"CellChat"];
}
self.customCell.sender.text = [array objectAtIndex:indexPath.row];
[self.customCell layoutIfNeeded];
CGFloat height = [self.customCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
return height +1;
}
我的问题:当我测试应用程序时,它不会在正确的地方进行自动换行。为什么?它与UILabel类有关吗?
编辑:
谢谢,但我仍然无法工作。我没有错误,但是当我加载表视图时它不显示文本。目前,我的代码看起来像这样:
进口:
#import "ChatViewController.h"
#import "ChatTableViewCell.h"
@interface ChatViewController ()
@property (strong, nonatomic) ChatTableViewCell *customCell;
@end
下一步:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
UILabel *gettingSizeLabel = [[UILabel alloc] init];
gettingSizeLabel.font = [UIFont fontWithName:@"Arial" size:15];
PFObject *tempObject = [array objectAtIndex:indexPath.row];
gettingSizeLabel.text = [tempObject objectForKey:@"Sender"];
gettingSizeLabel.numberOfLines = 0;
CGSize maximumLabelSize = CGSizeMake(140, MAXFLOAT);
CGSize expectedSize = [gettingSizeLabel sizeThatFits:maximumLabelSize];
return expectedSize.height + (10*2);
}
我的cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifer = @"CellChat";
ChatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifer];
PFObject *tempObject = [array objectAtIndex:indexPath.row];
cell.sender.text = [tempObject objectForKey:@"Sender"];
cell.receptor.text = [tempObject objectForKey:@"Receptor"];
cell.sender.lineBreakMode = NSLineBreakByWordWrapping;
cell.sender.numberOfLines = 0;
return cell;
}
答案 0 :(得分:1)
修改强>
请勿在{{1}}
中使用self.customCell
相反,计算像这样的单元格高度:
- (CGFloat)tableView:tableView heightForRowAtIndexPath:indexPath
并且不要忘记设置
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
UILabel *gettingSizeLabel = [[UILabel alloc] init];
gettingSizeLabel.font = font;
gettingSizeLabel.text = [array objectAtIndex:indexPath.row]; // your text inside [array objectAtIndex:indexPath.row];
gettingSizeLabel.numberOfLines = 0;
CGSize maximumLabelSize = CGSizeMake(yourMaxWidth, MAXFLOAT);
CGSize expectedSize = [gettingSizeLabel sizeThatFits:maximumLabelSize];
return expectedSize.height /*then add your margin 'y' margin multiplied by two for the top and bottom margin*/;
}
希望这对你有所帮助,编码很快..干杯! :) 强>