polesen polesen - 5 months ago 13
iOS Question

Programmatically access UISwitch size without adding component


, it seems the width of a
has changed from
94px to 79px
. I use the width of that component to calculate how for to the right, to place it in a

Is there a way to ask, through the iOS API, what the width of a
is, WITHOUT adding it to a view yet?

My current thoughts are to keep the two widths I already know in defines, and then check against iOS version, and
if >=5
it should be 79px. But that won't work as well if the width of that component changes again sometime.


Yes, because a UISwitch is a control of fixed width and sets and determines its own size, you can simply create it using CGRectZero and then check its dimensions via its frame. This works in iOS4 and iOS5.

On iOS 4 you get a width of 94px and on iOS 5 you will get the width of 79px. You do this like so:

UISwitch *mySwitch = [[[UISwitch alloc] initWithFrame:CGRectZero] autorelease];
width = mySwitch.frame.size.width;

You can then use the width value to position accordingly in the parent view. Do that by setting the desired x,y position on the UISwitch frame.

Also I suggest you DO set AutoResizingMask margin values on the UISwitch so that it remains in the position you place it regardless of device orientation or type.