繁体   English   中英

我如何使视图自动调整大小以适合Superview

[英]how can i make view auto resize to fit to superview

我有2个意见

首先是view1大小为100x100

第二个是view2大小是200 x200

我的代码是

[view1 addSubview:view2];

但view2的大小大于view1

我怎样才能使view2变小以适合view1的大小

谢谢

实现此目的的现代方法是使用自动布局。 这样,无论视图如何旋转或更改,它们都将保持不变。

根据您的设置,可能是这样的

NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:view2 attribute:NSLayoutAttributeWidth multiplier:1.f constant:0.f];

NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:view2 attribute:NSLayoutAttributeHeight multiplier:1.f constant:0.f];

[view1 addConstraints:@[widthConstraint,heightConstraint]];

如果需要使用较早的操作系统,则将帧设置为相等,然后使用autoresizingMask

当您想将较大的子视图放入较小的父视图中时,则:
1.使两个视图的size相同/相等。
2.将子视图的原点设为(0,0)。 由于frame属性在其超级视图的坐标系中占据视图的位置,因此对于子视图,原点将为(0,0)。

对于您的情况,您可以执行以下操作:

UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, view1.frame.size.width, view1.frame.size.height)];  
[view1 addSubview:view2];

要么

UIView *view2 = [[UIView alloc] initWithFrame:view1.bounds];  
[view1 addSubview:view2]; 

当您想在较小的超级视图(UIView)中缩小较大的图像(UIImageView)时,这确实很有用。

UIView类参考

视图可以嵌入其他视图并创建复杂的视觉层次结构。 这将在要嵌入的视图(称为子视图)和进行嵌入的父视图(称为超级视图)之间创建父子关系。 通常,子视图的可见区域不会被裁剪到其父视图的边界,但是在iOS中,您可以使用clipsToBounds属性来更改该行为。 父视图可以包含任意数量的子视图,但是每个子视图只有一个超级视图,该超级视图负责适当地放置其子视图。

并从frame property reference

框架矩形,用于描述视图在其超级视图的坐标系中的位置和大小。

并从bounds property reference

边界矩形,用于描述视图在其自己的坐标系中的位置和大小

所以你应该设置你的view1.frameview2.bounds

[view1 setBounds:CGRectMake(`x`,`y`,`width`,`height`)];

要么

[view2 setFrame:CGRectmake(`x`,`y`,`width`,`height`)];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM