[英]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.