我有两个 UIView
s,比如说 containerView
和 testView
.说testView
的宽度大于 containerView
.在这种情况下,当我添加 testView
作为 containerView
的 subview ,我的问题来了。 testView
的框架超出 containerView
的范围.这是我的代码 -
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(60, 154, 200, 200)];
containerView.backgroundColor = [UIColor grayColor];
containerView.clipsToBounds = NO;
UIView *testView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 260, 100)];
testView.backgroundColor = [UIColor yellowColor];
testView.layer.borderWidth = 3;
testView.layer.borderColor = [[UIColor blackColor] CGColor];
testView.center = CGPointMake(containerView.frame.size.width / 2, containerView.frame.size.height / 2);
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 25, 230, 50)];
label.text = @"This is a Label to test the size";
[testView addSubview:label];
[containerView addSubview:testView];
[self.view addSubview:containerView];
}
此代码的输出是 -
当
containerView.clipsToBounds = YES;
,输出为 -但我真正需要的是——
(编辑后的图像)
当我添加
testView
其宽度/高度大于其父 View - containerView
,testView
的框架(包括 child )应进行调整,使其完全适合其 super View 。我欢迎你的想法..!
最佳答案
执行此操作的现代方法是创建 View ,向 View 添加约束以建立与包含 View 的关系,然后将该 View 添加为 subview 。
这样你就不会弄乱框架,并且会为你处理旋转调整大小。
编辑添加
这是一些示例代码,可以执行类似于您要求的操作
- (void)viewDidLoad {
[super viewDidLoad];
// Create the containing view
UIView *greyView = [[UIView alloc] initWithFrame:CGRectZero];
greyView.backgroundColor = [UIColor grayColor];
greyView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:greyView];
// Create the label to go into the containing view
UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
label.translatesAutoresizingMaskIntoConstraints = NO;
label.text = @"Example Text";
label.backgroundColor = [UIColor yellowColor];
[greyView addSubview:label];
NSDictionary *bindings = NSDictionaryOfVariableBindings(greyView, label);
// Set the constraints for the greyView relative to it's superview - to cover completely
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[greyView]|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:bindings]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[greyView]|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:bindings]];
// Set the constraints for the label to be pinned equally with padding
[greyView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(30)-[label]-(30)-|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:bindings]];
[greyView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(30)-[label]-(30)-|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:bindings]];
}
如果您想看到它的实际效果并自己调整约束,我已经上传了 simple example project你可以使用。
关于iphone - 调整 UIView 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19223959/