ios - 动态调整大小 "container"UIView

标签 ios objective-c user-interface uiview

将动态数量的子 UIView 元素添加到“容器”UIView 时,我的 UI 遇到了问题。基本上,我需要能够动态调整容器 View (下面的 self.containerAView)的大小,以适应已添加到其中的所有“子” subview 的高度。到目前为止,我所做的所有重置框架的尝试都没有奏效。值得注意的是,初始大小在 *.xib 文件中定义,该文件初始加载 containerAView (UIView) 元素,初始大小为 300x200 (w x h)。

- (void)drawScreen {
    // handle all screen presentation initialization here
    // programatically create a dynamic number of child views to add to the container view
    for (int i = 0; i < 3; i++) {
        int childViewHeight = 60;
         int childViewWidth = 300;

        UIView *childView = [[UIView alloc] initWithFrame:CGRectMake(0, (i * childViewHeight) + (i * 10), childViewWidth, childViewHeight)];
    childView.backgroundColor = [UIColor blackColor];

    [self.containerAView addSubview:childView];
    }

    // build a mapping dictionary for all child elements in the container view
    NSMutableDictionary *containerASubViewDictionary = [[NSMutableDictionary alloc] init];
    for (int i = 0; i < [self.containerAView.subviews count]; i++) {
        [containerASubViewDictionary setValue:self.containerAView.subviews[i] forKey:[NSString stringWithFormat:@"childView%d", i]];
    }

    // WHAT TO ADD HERE TO HANDLE RESIZING self.containerAView height???
}

任何关于动态调整容器 View 大小的帮助都将不胜感激,因为到目前为止我还没有找到任何解决方案。

最佳答案

一种方法(可能是最新的方法)是在界面构建器中向容器 View 添加 4 个自动布局约束。

添加四个约束:x = 0, y = 0, width = 300 & height = 200

现在单击界面生成器中的宽度约束以突出显示它,然后控制将其拖动到您的 .h 文件中并为其命名,例如 containerWidth。

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *containerWidth;

重复高度。

在您的 .m 文件中,您可以通过操作约束来调整 drawScreen 方法中的高度和宽度。
self.containerWidth.constant = width; // your calculated new width
self.containerHeight.constant = height; // your calculated new height

关于ios - 动态调整大小 "container"UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23399067/

相关文章:

iphone - 应用程序 :didFinishLaunchingWithOptions: memory management

ios - MediaPlayer 使用 DropBox URL 播放视频

Android-显示全局应用信息

python - 向现有 python 脚本添加浏览器功能

ios - 旋转文本 MeshResource 使其不会被镜像

ios - NSString 中出现奇怪的竖线字符

ios - 更改不可见的自定义 UITableviewCell 中的项目

iphone - iOS获取当前wlan网络名称

android - 在显示 UI 的 android 服务中检测 'home button pressed' 事件(类似于 facebook 聊天头)

ios - Safari 服务崩溃 [SFAuthenticationViewController dismissViewControllerAnimated :completion:]