简体   繁体   English

获取iOS视图的实际尺寸

[英]Get actual dimensions of iOS view

How would I get the actual dimensions of a view or subview that I'm controlling? 我如何获得我正在控制的视图或子视图的实际尺寸? For example: 例如:

UIView *firstView = [[UIView alloc] initWithFrame:CGRectMake(0,0,200,100)];
[self addSubview:firstView];

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 20, 230, 120)];
[firstView addSubview:button];

As you can see, my button object exceeds the dimensions of the view it is being added to. 如您所见,我的button对象超出了要添加到的视图的尺寸。

With this is mind (assuming there are many objects being added as subviews), how can I determine the actual width and height of firstView ? 考虑到这一点(假设有许多对象被添加为子视图),我如何确定firstView的实际宽度和高度?

If you would like to have the button have the same width and height as firstView you should use the bounds property of UIView like this: 如果您希望按钮具有与firstView相同的宽度和高度,则应使用UIView的bounds属性,如下所示:

UIView *firstView = [[UIView alloc] initWithFrame:CGRectMake(0,0,200,100)];
[self addSubview:firstView];

UIButton *button = [[UIButton alloc] initWithFrame:firstView.bounds];
[firstView addSubview:button];

To just get the width/height of firstView you could do something like this: 要获得firstView的宽度/高度,您可以执行以下操作:

CGSize size = firstView.bounds.size;
NSInteger width = size.width;
NSInteger height = size.height;

The first view really is 200 x 100. However, the views inside are not clipped unless you use clipsToBounds . 第一个视图确实是200 x 100.但是,除非使用clipsToBounds否则不会剪切内部clipsToBounds

A preferable solution to your problem is to stop adding views that exceed the dimensions or to stop resizing views so that they overflow the available space, as appropriate. 解决问题的首选方法是停止添加超出维度的视图或停止调整视图大小,以便它们在适当的时候溢出可用空间。

(To actually calculate the full bounds including all subviews in the hierarchy is not hard, just a lot of work that won't actually get you anywhere. UIView happens to allow views to be larger than their containers, but it doesn't necessarily give any guarantees about what will work correctly and is likely to be a source of bugs if taken advantage of. The reason for clipsToBounds is probably that clipping is expensive but necessary during animation where subviews may be temporarily moved out of bounds for the purposes of an effect before they are removed from the view.) (实际计算包括层次结构中所有子视图的完整边界并不难,只是很多工作实际上不会让你到任何地方UIView碰巧允许视图比它们的容器大,但它不一定给出关于什么会正常工作的任何保证,如果被利用,很可能成为错误的来源clipsToBounds的原因可能是剪辑是昂贵的,但在动画期间必须临时移出界限以实现效果在将它们从视图中删除之前。)

firstview.frame.size.width firstview.frame.size.height

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

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