0

So I'm trying to add a UISwitch to my table cells on the right. I first tried adding it to the accesoryView, but when I entered to editing mode in the table, the UISwitch dissapeared. So now I added it to the contentView, which is working great, no dissapearing. But it adds it to the top left corner.

So I'm trying to add it to the right but I want to stay away of absolute values in order to support all sizes and orientations.

So I'm trying with this code:

[[cell contentView] addSubview:switchView];
switchView.frame = CGRectMake(cell.contentView.frame.size.width - 
                                    switchView.frame.size.width, 
                              0,
                              switchView.frame.size.width, 
                              switchView.frame.size.height);

But this is what I'm getting:

enter image description here

Any ideas how can I fix this?

Community
  • 1
  • 1
Jan
  • 2,462
  • 3
  • 31
  • 56
  • 2
    I think you should try create Custom Cell, and use autoresize properties for the controls you add in the cell, so that on rotation the controls adjust by themselves. – iphonic Aug 26 '13 at 07:08
  • Mmm... I could. But I'm trying to do it all in code IF possible. If I don't get any good answers, I'll definitely go that route. Thanks for the advice! – Jan Aug 26 '13 at 07:12

1 Answers1

2

You need to set the appropriate autoresizing masks or layout constraints on the switch.

If you're using springs and struts, you want the switch to have a flexible left margin only. This will keep it a fixed distance from the right hand edge of your superview - the content view is very likely resized between you adding the switch and it appearing on the screen.

To set this mask:

switchView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin; 

If you're using Auto layout (which makes not using specific frame values very easy!), you need to pin the switch to the right edge of the superview - [switch]-| in visual format.

jrturton
  • 118,105
  • 32
  • 252
  • 268
  • I'm actually using neither! As I'm doing it all by code. If I don't get any code-only solutions and I end up going this route, I'll award the answer to you. Thanks! – Jan Aug 26 '13 at 07:33
  • 2
    This is a code-only solution. You can set autoresizing masks or layout constraints in code. All views have a default autoresizing mask, which usually favours pinning to the top and left. I'll edit the answer. – jrturton Aug 26 '13 at 07:35