在UITableViewCell中使用textLabel

时间:2014-10-03 19:48:22

标签: ios objective-c uitableview

我有一个UITableView单元格,有一些文字而且太长了所以我希望它能自动调整大小。这是我尝试过的:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

//set colors
UIColor *garnetColor = [UIColor colorWithRed:85.0f/255.0f green:0/255.0f blue:3/255.0f alpha:1.0];
UIColor *garnetOffSetColor = [UIColor colorWithRed:127.0f/255.0f green:1/255.0f blue:6/255.0f alpha:1.0];

UIColor *uAlbanyGoldColor = [UIColor colorWithRed:175.0f/255.0f green:120/255.0f blue:40/255.0f alpha:1.0];
UIColor *uAlbanyGoldOffSetColor = [UIColor colorWithRed:190.0f/255.0f green:135/255.0f blue:40/255.0f alpha:1.0];
//    UIColor *uAlbanyPurpleColor = [UIColor colorWithRed:78/255.0f green:26/255.0f blue:128/255.0f alpha:1.0];

UIColor *RPIRedColor = [UIColor colorWithRed:158/255.0f green:8/255.0f blue:3/255.0f alpha:1.0];
UIColor *RPIRedOffSetColor = [UIColor colorWithRed:206/255.0f green:12/255.0f blue:12/255.0f alpha:1.0];

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    cell.textLabel.adjustsFontSizeToFitWidth = YES;

    }
   //more code for the cells

}

那么还有另一种调整文本大小的方法吗?

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

使用此

cell.textLabel.adjustsFontSizeToFitWidth = YES;

答案 1 :(得分:0)

adjustsFontSizeToFitWidth不适合你。

您需要使用heightForRowAtIndexPath方法。以下是该方法的示例。

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

float cellHeight = [STRING_THAT_YOU_WANT_TO_DISPLAY sizeWithFont:COMMENT_FONET_NEW constrainedToSize:CGSizeMake(contentWidth - 65 - 10 - 10, 400)].height;

return cellHeight ;

}

希望它适合你:)

答案 2 :(得分:0)

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
   CGSize maximumCellSize = CGSizeMake(maximumCellWidth, maximumCellHeight);  // (200, 1000) for example
   CGRect textRect = [textToShow boundingRectWithSize:maximumCellSize
                                        options:(NSStringDrawingUsesLineFragmentOrigin)
                                     attributes:@{NSFontAttributeName:[UIFont fontWithName:@"System" size:15]} // attributes of textToShow
                                        context:nil];
    return textRect.size.height + sumOfHeightsOfOtherConstantStuffInCell;
}
相关问题