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.

With this is mind (assuming there are many objects being added as subviews), how can I determine the actual width and height of 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:

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:

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 .

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.)


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

链接地址: http://www.djcxy.com/p/69314.html

上一篇: 调试揭示模块模式:功能不在范围内直到被调用?

下一篇: 获取iOS视图的实际尺寸