14

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.

toadflakz
  • 7,764
  • 1
  • 27
  • 40
polesen
  • 713
  • 1
  • 6
  • 18

3 Answers3

25

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.

Cliff Ribaudo
  • 8,932
  • 2
  • 55
  • 78
  • 6
    Or for positioning the UISwitch in the cell you can simply add the Switch as the AccessoryView. eg. myTableViewCell.accessoryView = mySwitch. This has the added benefit of always positioning it to the right and properly handling its size regardless of iOS version. – Cliff Ribaudo Nov 08 '11 at 10:40
0

Swift solution:

let size = UISwitch.size()

With extension

private var switchSize: CGSize?
extension UISwitch {
  class func size() -> CGSize {
    if let size = switchSize {
      return size
    } else {
      let view = UISwitch(frame: CGRectZero)
      switchSize = view.frame.size
      return view.frame.size
    }
  }
}
Dmitry Kozlov
  • 1,115
  • 10
  • 14
0

Starting in iOS 6.0, you can use intrinsicContentSize to get the natural size for a UISwitch instance.

Roman Podymov
  • 4,168
  • 4
  • 30
  • 57