Jan
Jan

Reputation: 2522

How to properly position a UITableView cell subview to the right?

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?

Upvotes: 0

Views: 1910

Answers (1)

jrturton
jrturton

Reputation: 119242

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.

Upvotes: 2

Related Questions