Weird looking UISwitch in UITableViewCell

102 views Asked by At

I added a UISwitch as a subview to the contentView of a UITableViewCell and set isOn to be true. After toggling it, it becomes the following and looks weird.

Does anyone know why this might happen and how to solve this problem?

Weird UISwitch: https://dl.dropboxusercontent.com/u/43497092/stackOverflow/Screen%20Shot%202015-06-12%20at%209.28.43%20AM.png

For comparison, a normal looking UISwitch would look like this:

Normal UISwitch: https://dl.dropboxusercontent.com/u/43497092/stackOverflow/Screen%20Shot%202015-06-12%20at%209.32.43%20AM.png

3

There are 3 answers

0
AudioBubble On BEST ANSWER

You really want to your switch to be part of your custom UITableViewCell class, and be created as part of the cell instantiation. You can then access the switch via a property of the dequeued cell.

layoutSubviews is not the place to be adding controls. You probably don't even need to override it, since Auto Layout constraints can take care of the switch's layout.

0
riven On

This happened because I add a new switch each time when "layoutSubviews" is called. When the value of the switch changes, a new switch is added on top of the previous switch.

The solution is to remove the previous switch from super view, and then add the new switch to the view.

0
Pokemon On
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

and define when cell value is equal to nil. Then , switch will not be like that.