我有一个UiSwitch,我想禁止它由用户打开和关闭。我想知道用户何时点击它,并根据需要以编程方式更改其状态。
此代码禁用开关,但使其褪色。我不想要它,因为我希望用户点击它。
@Database(entities = {Entity.class}, version = 1)
@TypeConverters(DateConverter.class)
public abstract class AppDatabase extends RoomDatabase {...}
答案 0 :(得分:1)
无论出于何种原因,您都可以通过在开关上添加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];
}
答案 1 :(得分:1)
您可以执行以下操作,主要的想法是找到开关的坐标。如果您在视图中进行切换,则可以改用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