Get actual dimensions of iOS view
Asked Answered
K

3

7

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?

Kenney answered 13/2, 2013 at 13:5 Comment(4)
It's 230 and 120, respectively, I don't see what your problem is.Heloise
firstView.bounds.size.height(width) give its sizeDamato
@H2CO3 it's not though is it, it's 240 and 140 due to the x and y positioning of button. Anyway, that wasn't the question.. With programmatic additions of subViews that exceed the bounds of the target view, can you calculate the actual bounds of the original UIView?Kenney
@Kenney Do you mean by accident the CGRectIntersection() function?Heloise
M
4

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;
Moorhead answered 13/2, 2013 at 13:9 Comment(0)
F
0

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

Fries answered 13/2, 2013 at 13:9 Comment(0)
N
0

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

Neptunian answered 13/2, 2013 at 13:11 Comment(1)
frame might not work that well if the view has rotated... see #5361869Impeccant

© 2022 - 2024 — McMap. All rights reserved.