【发布时间】:2014-05-04 11:17:15
【问题描述】:
我有一个自定义UITableViewCell,它有两个UILabels 和一个UIImageView。我根据来自 Web 服务的数据对象设置每个 UILabel's 文本。因此,直到运行时才知道文本的大小,因为它可能是来自我的 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;
}
【问题讨论】:
-
改用
UITextView。 -
sizeToFit怎么了? -
sizeToFit 未被弃用,请查看文档。