[英]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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.