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/

相关文章:

iOS 崩溃,EXC_BREAKPOINT,Xcode 6.1 无线索

ios - XCode 开发者数据

ios - 如何检查UIButton的背景色

iphone - 代码设计错误 : Certificate identity appearing twice

ios - swift 4 : @IBOutlet UITextView crash

ios - 打开设置应用程序

ios - 使用 NSSortDescriptor 在 iOS 中对包装对象数组进行排序

java - 绘制到屏幕外图像

Silverlight 开发人员想要获得一些设计师的资格 - 我从哪里开始?

java - Gwt,如何使文本框具有多于 1 条可见行?