问题描述
如何修改 The iPhone Developer's Cookbook 第 6 章09a - PrefsTable"配方中的以下代码段(在 tableView:cellForRowAtIndexPath: UITableViewController 方法中):
How would one modify the following snippet (in a tableView:cellForRowAtIndexPath: UITableViewController method) from the "09a - PrefsTable" recipe from Chapter 6 of The iPhone Developer's Cookbook:
if (row == 1) {
// Create a big word-wrapped UILabel
cell = [tableView dequeueReusableCellWithIdentifier:@"libertyCell"];
if (!cell) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"libertyCell"] autorelease];
[cell addSubview:[[UILabel alloc] initWithFrame:CGRectMake(20.0f, 10.0f, 280.0f, 330.0f)]];
}
UILabel *sv = [[cell subviews] lastObject];
sv.text = @"When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.";
sv.textAlignment = UITextAlignmentCenter;
sv.lineBreakMode = UILineBreakModeWordWrap;
sv.numberOfLines = 9999;
return cell;
}
...要调整sv" UILabel 子视图和单元格" UITableViewCell 的大小,使其大小刚好适合文本(并处理更多或更少的文本,以及其他类型的文本对齐方式)?我查看了 UILabel textRectForBounds:limitedToNumberOfLines: 方法,但文档指出不应直接调用它(并且只能覆盖).我尝试了 UIView sizeToFit 方法,但没有成功.
...to size the "sv" UILabel subview and the "cell" UITableViewCell to be sized just big enough to fit the text (and work with more or less text, and other types of text alignment)? I looked at the UILabel textRectForBounds:limitedToNumberOfLines: method, but the documentation states that it should not be called directly (and should only be overridden). I experimented with the UIView sizeToFit method, without success.
更新: 我问了一个关于 NSString -sizeWithFont:forWidth:lineBreakMode: 方法 的问题的新问题.
推荐答案
我不得不这样做,以至于我扩展了 UILabel 来为我做:
I had to do this enough that I extended UILabel to do it for me:
@interface UILabel (BPExtensions)
- (void)sizeToFitFixedWidth:(CGFloat)fixedWidth;
@end
@implementation UILabel (BPExtensions)
- (void)sizeToFitFixedWidth:(CGFloat)fixedWidth
{
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, fixedWidth, 0);
self.lineBreakMode = NSLineBreakByWordWrapping;
self.numberOfLines = 0;
[self sizeToFit];
}
@end
然后让标签具有可变的多行高度但固定的宽度:
then to have a label to have a variable multiline height but a fixed width just:
[myLabel sizeToFitFixedWidth:kSomeFixedWidth];
这篇关于调整 UILabel 的大小以适合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!