简体   繁体   English

如何以编程方式设置子视图的框架以使其适合其父视图?

[英]How to programmatically set a subview's frame to fit it inside its superview?

I need to programmatically do the following. 我需要以编程方式执行以下操作。 How can I do this? 我怎样才能做到这一点? The code should be dynamic enough to fit a portrait view inside landscape also. 该代码应具有足够的动态性,以适合横向内的纵向视图。 The views are not UIImageViews. 这些视图不是UIImageViews。 在此处输入图片说明

If you don't mind including the AVFoundation framework in your project, you can use: AVMakeRectWithAspectRatioInsideRect(CGSize aspectRatio, CGRect boundingRect); 如果您不介意在项目中包括AVFoundation框架,则可以使用: AVMakeRectWithAspectRatioInsideRect(CGSize aspectRatio, CGRect boundingRect);

Its documentation states: 其文档指出:

Returns a scaled CGRect that maintains the aspect ratio specified by a CGSize within a bounding CGRect. 返回缩放的CGRect,该缩放的CGRect在边界CGRect中保持CGSize指定的宽高比。

It can be used as: 它可以用作:

subview.frame = AVMakeRectWithAspectRatioInsideRect(subview.bounds.size, superview.bounds);

Parameters: 参数:

aspectRatio : The width and height ratio (aspect ratio) you want to maintain. AspectRatio :您要保持的宽高比(纵横比)。

boundingRect : The bounding rectangle you want to fit into. boundingRect :您要适合的边界矩形。

float ratio = subView.bounds.size.height/subView.bounds.size.width;

[subView setFrame:CGRectMake(0,0,superView.bounds.size.width,superView.bounds.size.width*ratio)];
[subView setCenter:CGPointMake(superView.bounds.size.width/2,superView.bounds.size.height/2)];

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

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