我有一个自定义的 UITableViewCell
,它有两个 UILabels
和一个 UIImageView
。我根据来自 Web 服务的数据对象设置每个 UILabel 的
文本。因此,在运行时之前,无法知道文本的大小,因为它可能是来 self 的 Web 服务调用的任何内容。
有没有办法告诉 UILabel
根据其文本大小或内容自动调整其大小?
更新
好吧,出于某种原因,所有建议的方法都没有对 UITableViewCell 中的 UILabel 进行任何更改。
我在下面的代码中设置文本:
使用 SujithPt 方法的示例:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
BBCategoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CategoryCell"];
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CategoryCell" owner:self options:nil];
cell = [topLevelObjects objectAtIndex:0];
BBFilterCategoryObject *category = self.categories[indexPath.row];
cell.title.text = category.category.name;
CGSize labelSize = [self getSizeForText:cell.title.text maxWidth:150 font:@"ChaparralPro-Bold" fontSize:15];
[cell.title sizeThatFits:labelSize];
return cell;
}
- (CGSize)getSizeForText:(NSString *)text maxWidth:(CGFloat)width font:(NSString *)fontName fontSize:(float)fontSize {
/*! Returns the size of the label to display the text provided
@param text
The string to be displayed
@param width
The width required for displaying the string
@param fontName
The font name for the label
@param fontSize
The font size for the label
*/
CGSize constraintSize;
constraintSize.height = MAXFLOAT;
constraintSize.width = width;
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:fontName size:fontSize], NSFontAttributeName,
nil];
CGRect frame = [text boundingRectWithSize:constraintSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributesDictionary
context:nil];
CGSize stringSize = frame.size;
return stringSize;
}
最佳答案
使用这个方法:
/*! Returns the size of the label to display the text provided
@param text
The string to be displayed
@param width
The width required for displaying the string
@param fontName
The font name for the label
@param fontSize
The font size for the label
*/
- (CGSize)getSizeForText:(NSString *)text maxWidth:(CGFloat)width font:(NSString *)fontName fontSize:(float)fontSize {
CGSize constraintSize;
constraintSize.height = MAXFLOAT;
constraintSize.width = width;
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:fontName size:fontSize], NSFontAttributeName,
nil];
CGRect frame = [text boundingRectWithSize:constraintSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributesDictionary
context:nil];
CGSize stringSize = frame.size;
return stringSize;
}
编辑
使用上述方法返回的尺寸设置标签框。
[cell.title setFrame:CGRectMake(cell.title.frame.origin.x, cell.title.frame.origin.y, sizeFromTheMethod.height, sizeFromTheMethod.width)];
关于ios - UILabel 根据文字大小自动调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22654476/