UITableViewCell中的UILabel没有使用自动布局调整大小?

时间:2014-12-23 10:01:25

标签: ios objective-c uitableview uilabel

我正在使用自动布局。在自定义UITableViewCell中添加了UILabel,其中包含最大宽度。我尝试了很多方法,以便文本更少。它应该缩小,或者如果文本更多,它应该增加标签的高度。

我尝试在UILabel中制作CellForRowAtIndex,这显然是个坏主意。 然后我尝试使用Font的帮助CGSize标签宽度。它缩小但它不合适并且为了实现它我必须重新绘制约束。基本上我尝试的解决方案在视觉上并不吸引人。请帮帮我。我附上了屏幕当前状态的图片

感谢enter image description here

1 个答案:

答案 0 :(得分:1)

//Array of name
NSMutableArray *nameArray;

//take outlet of height constraint in custom cell; 
@property(weak) IBOutlet NSLayoutConstraint *labelHeightConstraint;


-(void)viewDidLoad
{
_nameArray=[NSMutableArray arrayWithObjects:,@"I am using Auto-layout. In Custom     UITableViewCell added a UILabel with max width.",@"Hi I am Rohit",@"I Like To Help Society" ,nil];
}


- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomerRatingsCell *customerRatingsCell=[tableView dequeueReusableCellWithIdentifier:@"CustomerRatingsIdentifier"];
customerRatingsCell.labelName=[_nameArray objectAtIndex:indexPath.row];
customerRatingsCell.headerLabelConstraint=[self getLabelHeight:[NSString stringWithFormat:@"%@",[_nameArray objectAtIndex:indexPath.row]]];
return CustomerRatingsCell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

      return [self getLabelHeight:[NSString stringWithFormat:@"%@",[_nameArray objectAtIndex:indexPath.row]]]+25 ;//plus 25 is remaining space apart from label height, if you are using the full height label equals to cell height then don't add it.

}



- (CGFloat)getLabelHeight:(NSString*)textLabel
{
    CGRect textRect = [textLabel boundingRectWithSize:CGSizeMake(300, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont fontWithName:Avenir Roman size:12.0f]} context:nil];

    CGSize  expectedLabelSize = CGSizeMake(textRect.size.width, textRect.size.height);

    return expectedLabelSize.height;
}