Programmatically access UISwitch size without adding component

polesen picture polesen · Oct 14, 2011 · Viewed 10.5k times · Source

In iOS5, it seems the width of a UISwitch 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 UITableViewCell.

Is there a way to ask, through the iOS API, what the width of a UISwitch 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.

Answer

Cliff Ribaudo picture Cliff Ribaudo · Nov 6, 2011

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.