Objective-C 如何以编程方式而不是用户控制 UISwitch 的状态?

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

我有一个 UiSwitch,我想禁止它被用户打开和关闭。我想知道用户何时点击它,并根据需要以编程方式更改其状态。

此代码禁用开关但使其褪色。我不想要它,因为我希望用户点击它。

[switch setEnabled:NO];

无论出于何种原因,您都可以通过在开关上添加 UIView 并向其添加点击识别器来处理点击来实现它,然后您可以通过编程方式将开关设置为打开或关闭。考虑以下代码:

- (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];
}

你可以这样做,主要思想是找到开关的坐标。如果您在视图中有开关,则可以改用 hitTest:withEvent: 方法

#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