Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically access UISwitch size without adding component

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.

like image 233
polesen Avatar asked Oct 14 '11 07:10

polesen


People also ask

How do you set UISwitch state programmatically?

If you are using a UISwitch, then as seen in the developer API, the task setOn: animated: should do the trick. Show activity on this post. UISwitches have a property called "on" that should be set.

How do I reduce the size of the UISwitch?

Not possible. A UISwitch has a locked intrinsic height of 51 x 31 . You can force constraints on the switch at design time in the xib... but come runtime it will snap back to its intrinsic size.


1 Answers

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.

like image 99
Cliff Ribaudo Avatar answered Sep 23 '22 12:09

Cliff Ribaudo