Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom UISwitch with image [closed]

I need to implement a custom switch in a project. Currently what I have found is that we cannot alter with UISwitch in way to implement as shown in below image. I've followed posts and googled through stackoverflow and other blogs but didn't found a solution as desired. One way is to go with UISegmented control as in this post, but that too doesn't solves my problem.

enter image description here

Thanks in advance for any help

like image 860
Arshad Parwez Avatar asked Apr 29 '13 14:04

Arshad Parwez


People also ask

What is a uiswitch control?

A control that offers a binary choice, such as on/off. The UISwitch class declares a property and a method to control its on/off state. As with UISlider, when the user manipulates the switch control (“flips” it), it triggers the valueChanged event.

How do I customize the appearance of the switch?

You can customize the appearance of the switch by changing the color used to tint the switch when it is on or off. For information about basic view behaviors, see View Programming Guide for iOS.

What happens when you flip a switch in Uis?

As with UISlider, when the user manipulates the switch control (“flips” it) a valueChanged event is generated, which results in the control (if properly configured) sending an action message. You can customize the appearance of the switch by changing the color used to tint the switch when it is on or off.


2 Answers

It's not hard to create your own switch. A UISwitch is a control — essentially just a view that sends a message — with two states. You could set it up your own custom control like this:

  • container view: a simple view with rounded corners (set the cornerRadius of the view's layer) and a background color

  • left image: an image view that displays the image you want to show on the left side, i.e. the check mark for your example

  • right image: an image view that displays the image you want to show on the right side, i.e. the X mark for your example

  • slider: an image view showing the slider portion of the switch, set above the other two image views

When the user taps or swipes the control, use Core Animation to move the slider to the other side of the switch and update the state of the control and do a quick fade to the background color for the new state. Send the control's action to the target.

like image 128
Caleb Avatar answered Oct 24 '22 02:10

Caleb


As gasparuff says, you can also do it with a UIButton, just set the images:

[button setImage:[UIImage imageNamed:@"image_on"] forState:UIControlStateSelected];
[button setImage:[UIImage imageNamed:@"image_off"] forState:UIControlStateNormal];

and when it's tapped just toggle the selected property.

- (void) buttonTap {
    button.selected = !button.selected;
}

Which will change the images automatically.

like image 26
Odrakir Avatar answered Oct 24 '22 02:10

Odrakir