Fattaneh Talebi
Fattaneh Talebi

Reputation: 777

How to control the state of UISwitch programmatically and not by user in Objective-C?

I have a UiSwitch, which I want to disable it from being on and off by user. I want to be aware when user taps on it, and change its state programmatically if I want.

This code disables the switch but makes it faded. I don't want it because I want user tap on it.

[switch setEnabled:NO];

Upvotes: 0

Views: 538

Answers (2)

schmidt9
schmidt9

Reputation: 4538

You can do something like this, the main idea is to find coordinates of the switch. If you have your switch in a view you can use hitTest:withEvent: method instead

#import "ViewController.h"

@interface ViewController ()

@property (strong, nonatomic) IBOutlet UISwitch *mySwitch;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.mySwitch.userInteractionEnabled = NO;
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesEnded:touches withEvent:event];

    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];

    if (CGRectContainsPoint(self.mySwitch.frame, touchLocation)) {
        [self.mySwitch setOn:!self.mySwitch.isOn];
    }
}

@end

Upvotes: 1

gulyashki
gulyashki

Reputation: 459

For whatever reason you might want to do that, one way to achieve it by adding UIView over the switch and add a tap recognizer to it to handle the tap, then you can set the switch on or off programatically. Consider the code below:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.switchControl = [[UISwitch alloc] initWithFrame:CGRectMake(10, 100, 0, 0 )];
    [self.view addSubview:self.switchControl];
    [self.switchControl setOn:YES animated:NO];

    UIView *view = [[UIView alloc] initWithFrame:self.switchControl.frame];
    [self.view addSubview:view];

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapSwitch)];
    [view addGestureRecognizer:tap];
}

- (void)didTapSwitch {
    [self.switchControl setOn:NO animated:YES];
}

Upvotes: 1

Related Questions