iphone - sizeThatFits 的正确使用方法 : and sizeToFit with UILabel?

标签 iphone resize uilabel sizetofit

目前,我使用 [aString sizeWithFont:constrainedToSize:lineBreakMode:] 正确调整了标签的大小,但我已将旋转引入到我的设备中,并且具有灵活的宽度和高度,这会导致我的 UILabel 拉伸(stretch)宽度方式(因为它的相对于主视图设置),但不会收缩高度以补偿额外的空间。

在我问的另一个问题中,我被告知使用 sizeToFit 和/或 sizeThatFits: 但是我在互联网上找不到任何有用的资源来告诉我如何正确地使用它,我所做的试验会导致不合理的行为。

简而言之,假设我有这样的结构:

UIView *innerView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, self.view.frame.size.width-20, 0)];
[innerView setAutoresizingMask:*flexible width and height*]
[innerView setBackgroundColor:[UIColor redColor]];
[self.view addSubview:innerView];

UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, innerView.frame.size.width-20, 0)];
[myLabel setAutoresizingMask:*flexible width and height*]
[myLabel setBackgroundColor:[UIColor blueColor]];
[myLabel setNumberOfLines:0];
[myLabel setLineBreakMode:UILineBreakModeWordWrap];
[innerView addSubview:myLabel];

这是一个简化版本(同样作为免责声明,这不是我的实际代码,我意识到这些元素会泄漏以及其他所有内容......这只是一个示例,以便您可以看到结构)。

基本上我有这两个要素。现在,在旋转时,它们都会拉伸(stretch)以适应新的 View 尺寸。我需要的是一种增加或减少高度以动态适应内容的方法。 [aString sizeWithFont...] 只是静态的。那么我如何使用 sizeToFitsizeThatFits 来使其动态化?

谢谢。

汤姆

最佳答案

您是否尝试过在屏幕旋转后重置标签的框架?检查 interfaceOrientation 的值:

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation

然后,为didRotateFromInterfaceOrientation内的每种 View 模式相应地设置标签的框架。

以下是根据字符串长度调整标签框大小的示例:http://cocoamatic.blogspot.com/2010/08/uilabel-dynamic-sizing-based-on-string.html

关于iphone - sizeThatFits 的正确使用方法 : and sizeToFit with UILabel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4022611/

相关文章:

ios - 是否可以在 objective-c 中格式化字符串的特定部分?

iphone - 我在文本字段中输入的任何数字在标签中显示为 0

iphone - openAL 获取/设置偏移量(以秒为单位)

iphone - iPad 设备方向为空?

iphone - 来自字符串数组 iOS 的索引表

XCode images.assets Assets 目录切片被忽略,图像仍然失真

c# - 有哪些不同的方法可以在不使用水平或垂直对齐设置为左侧和顶部的情况下拖动和移动对象

image - 如何防止 ImageMagick Convert 放大图像*?

ios - 带背景的本地化 UILabel

ios - 应用程序试图在目标 <UIApplicationRotationFollowingController : 0x100c75280> 上呈现一个 nil 模态视图 Controller