Iphone 如何使视图自动调整大小以适应superview
我有两种观点 首先是view1,尺寸为100x100 第二种是view2,尺寸为200 x200 我的代码是Iphone 如何使视图自动调整大小以适应superview,iphone,objective-c,ios4,Iphone,Objective C,Ios4,我有两种观点 首先是view1,尺寸为100x100 第二种是view2,尺寸为200 x200 我的代码是 [view1 addSubview:view2]; 但view2的大小大于view1 如何使view2变小以适合view1的大小 谢谢来自 视图可以嵌入其他视图并创建复杂的视觉层次结构。这将在正在嵌入的视图(称为子视图)和执行嵌入的父视图(称为超级视图)之间创建父子关系。通常,子视图的可见区域不会剪裁到其superview的边界,但在iOS中,您可以使用clipsToBounds属性来
[view1 addSubview:view2];
但view2的大小大于view1
如何使view2变小以适合view1的大小
谢谢来自
视图可以嵌入其他视图并创建复杂的视觉层次结构。这将在正在嵌入的视图(称为子视图)和执行嵌入的父视图(称为超级视图)之间创建父子关系。通常,子视图的可见区域不会剪裁到其superview的边界,但在iOS中,您可以使用clipsToBounds属性来更改该行为。父视图可以包含任意数量的子视图,但每个子视图只有一个superview,superview负责正确定位其子视图
来自
框架矩形,用于描述视图在其superview坐标系中的位置和大小
来自
边界矩形,描述视图在其自身坐标系中的位置和大小因此,您应该设置
view1.frame
或view2.bounds
[view1 setBounds:CGRectMake(`x`,`y`,`width`,`height`)];
或
当您想在较小的superview中容纳较大的子视图时,则:
1.使两个视图的大小相同/相等。
2.将子视图的原点设为(0,0)。由于
frame
属性获取视图在其superview坐标系中的位置,因此子视图的原点将为(0,0)
对于您的情况,您可以这样做:
UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, view1.frame.size.width, view1.frame.size.height)];
[view1 addSubview:view2];
或
当您想在较小的超级视图(UIView)中缩小较大的图像(UIImageView)时,这非常有用。实现这一点的现代方法是使用自动布局。这样,无论视图如何旋转或更改,它们都将保持相同的大小 取决于你的设置,可能是这样的
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]];
如果需要针对早期的操作系统,请将帧设置为相等,并使用
自动ResizingMask
尝试覆盖布局子视图。更改视图层次结构时,请调用[view1 setNeedsLayout]。它将调用layoutsubview,在那里您可以访问每个子视图并调整其大小。读这个。不确切,但有点帮助。使用CGRectMake方法将视图2的帧大小设置为小于视图1的帧大小…从技术上讲,问题是如何使用自动调整大小而不是使用帧来实现这一点
UIView *view2 = [[UIView alloc] initWithFrame:view1.bounds];
[view1 addSubview:view2];
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]];