小编Fet*_*eta的帖子

使用autolayout将动态UIView设置为与容器视图匹配

我在IB中有一个UIView,其中有另一个UIView,我用它作为容器视图.在代码中,我创建了三个不同的视图,然后根据应用程序的状态将相应的视图设置为容器视图中的动画.在任何给定时间,三种不同视图中只有一种是有效的.问题是,当我在模拟器中运行不同的iPhone时,我的新子视图不会缩放以匹配容器视图.我正在使用autolayout.出于测试目的,我将我的子视图设置为一个大按钮,它的所有边缘都限制在超视图中.并且容器视图的边缘也受限于它的超视图.我想要的是子视图匹配容器的视图.即按钮拉伸容器视图的整个大小.当在不同的iPhone上运行时,容器视图的大小以及子视图应该相对于不同的iPhone屏幕大小按比例缩放.

下面是我用来初始化子视图并设置相对于容器视图的约束的代码.

UIView *containerView = self.subView;
UIView *newSubview = [[mySubview alloc] init];
[newSubview setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.containerView addSubview:newSubview];

[self.containerView addConstraint:[NSLayoutConstraint constraintWithItem:newSubview attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.containerView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]];

[self.containerView addConstraint:[NSLayoutConstraint constraintWithItem:newSubview attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.containerView attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0]];

[self.containerView addConstraint:[NSLayoutConstraint constraintWithItem:newSubview attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.containerView attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0]];

[self.containerView addConstraint:[NSLayoutConstraint constraintWithItem:newSubview attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.containerView attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0]];  
Run Code Online (Sandbox Code Playgroud)

我似乎无法让这个工作.我对autolayout很新,我不确定我做错了什么,并且想停止撞到这堵墙.任何帮助都会很棒.:)


*************附加信息**************


对不起,我没有尽可能清楚地说出我的问题.所以这里有更多关于屏幕截图的信息.首先,我将描述我在代码方面做了什么.

在AppDelegate.m中的didFinishLaunchingWithOptions中,我创建了这样的MyViewController,

self.myViewController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];
Run Code Online (Sandbox Code Playgroud)

在MyViewController.m中的viewDidLoad中,我创建了mySubview并将其添加到我的containerView并为此创建约束,

UIView *containerView = self.containerView;
UIView *mySubview = [[MySubview alloc] init];
[mySubview setTranslatesAutoresizingMaskIntoConstraints:NO];
[containerView addSubview:mySubview];

NSDictionary *views = …
Run Code Online (Sandbox Code Playgroud)

resize uiview ios autolayout

30
推荐指数
1
解决办法
7万
查看次数

标签 统计

autolayout ×1

ios ×1

resize ×1

uiview ×1