iPad/iPhone - 设置适合给定矩形的标签尺寸
在我的 iPad 应用程序中,我有一个占据整个视图的标签。我想动态计算适合整个矩形的标签的大小。但我想保持自动换行。 在我的 XIB 中,我添加了一个标签并将其模式设置为自动换行模式。
请参阅所附图片。我想要的是用自动换行显示标签。有人可以帮我找出问题所在吗?
以下是我正在使用的代码: (在这些论坛的答案之一中,我找到了以下代码:)
-(void)sizeLabel:(UILabel*)label toRect:(CGRect)labelRect withFont:(NSString*)fontName {
// Set the frame of the label to the targeted rectangle
label.frame = labelRect;
// Try all font sizes from largest to smallest font size
int fontSize = 300;
int minFontSize = 5;
// Fit label width wize
CGSize constraintSize = CGSizeMake(label.frame.size.width, MAXFLOAT);
do {
// Set current font size
label.font = [UIFont fontWithName:fontName size:fontSize];
// Find label size for current font size
CGSize labelSize = [[label text] sizeWithFont:label.font
constrainedToSize:constraintSize
lineBreakMode:UILineBreakModeWordWrap];
// Done, if created label is within target size
if( labelSize.height <= label.frame.size.height )
break;
// Decrease the font size and try again
fontSize -= 2;
} while (fontSize > minFontSize);
}
In my ipad application, i've a lable that occupies whole view. I want to dynamically calculate the size of the label that fits in the whole rect. But I want to maintain the word wrap.
In my XIB, I added a label and set it mode to word wrap mode.
See the image attached. What I want is to show the label with word wrap. Can some one help me to find the problem?
The following is the code that I'm using:
(In one of the answers in these forums, I found the following code:)
-(void)sizeLabel:(UILabel*)label toRect:(CGRect)labelRect withFont:(NSString*)fontName {
// Set the frame of the label to the targeted rectangle
label.frame = labelRect;
// Try all font sizes from largest to smallest font size
int fontSize = 300;
int minFontSize = 5;
// Fit label width wize
CGSize constraintSize = CGSizeMake(label.frame.size.width, MAXFLOAT);
do {
// Set current font size
label.font = [UIFont fontWithName:fontName size:fontSize];
// Find label size for current font size
CGSize labelSize = [[label text] sizeWithFont:label.font
constrainedToSize:constraintSize
lineBreakMode:UILineBreakModeWordWrap];
// Done, if created label is within target size
if( labelSize.height <= label.frame.size.height )
break;
// Decrease the font size and try again
fontSize -= 2;
} while (fontSize > minFontSize);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
所以你试图让文本自动换行,但使用最大可能的大小?
在这种情况下,请执行以下操作:
这应该就是您需要做的全部事情。
So you trying to get the text to be wordwrapped, but with the maximum possible size?
In that case do:
And that should be all you need to do.