前面有一篇有关蓝牙扫描枪实现原理的笔记 iOS 蓝牙扫描枪 这里用UITextField这个控件来实现蓝牙扫描的功能
话不多说,直接上代码
#import "ViewController.h"
@interface ViewController ()<UITextFieldDelegate>
@property (nonatomic, strong) UITextField *scanerTextField;
@end
@implementation ViewController
- (UITextField *)scanerTextField {
if (!_scanerTextField) {
_scanerTextField = [[UITextField alloc] init];
_scanerTextField.delegate = self;
_scanerTextField.spellCheckingType = UITextSpellCheckingTypeNo;
_scanerTextField.autocorrectionType = UITextAutocorrectionTypeNo;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0
if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 9.0) {
_scanerTextField.inputAssistantItem.leadingBarButtonGroups = @[];
_scanerTextField.inputAssistantItem.trailingBarButtonGroups = @[];
}
#endif
}
return _scanerTextField;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.scanerTextField becomeFirstResponder];
[self.view addSubview:self.scanerTextField];
}
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
NSLog(@"%@",textField.text);
return YES;
}
@end
思路很简单,就是使用UITextField这个控件来接收外接输入,蓝牙扫描枪相当于一个外接键盘。
之所以使用UITextField而不使用UITextView的原因时,使用UITextView的话,当iPad外接键盘和蓝牙扫码枪同时使用时,会有冲突,为了避免冲突使用UITextField,在- textFieldShouldReturn: 这个回调里处理扫描结果。
有时候使用蓝牙扫描枪的时候,需要隐藏系统键盘,只是不显示系统键盘,可以做如下处理
UIView *inputView = [[UIView alloc] initWithFrame:CGRectZero];
_scanerTextField.inputView = inputView;
这样当激活 scanerTextField 成为第一响应者时,就不会弹出键盘了。
代码如下:
- (UITextField *)scanerTextField {
if (!_scanerTextField) {
_scanerTextField = [[UITextField alloc] init];
_scanerTextField.delegate = self;
_scanerTextField.spellCheckingType = UITextSpellCheckingTypeNo;
_scanerTextField.autocorrectionType = UITextAutocorrectionTypeNo;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0
if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 9.0) {
_scanerTextField.inputAssistantItem.leadingBarButtonGroups = @[];
_scanerTextField.inputAssistantItem.trailingBarButtonGroups = @[];
}
#endif
UIView *inputView = [[UIView alloc] initWithFrame:CGRectZero];
_scanerTextField.inputView = inputView;
[inputView release];
}
return _scanerTextField;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if (textField.text && textField.text.length) {
...
}
return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
[NSObject cancelPreviousPerformRequestsWithTarget:self];
[self performSelector:@selector(setScannerKeyboardEditable) withObject:nil afterDelay:0.8];
}
- (void)setScannerKeyboardEditable {
if (_scanerEnable) {
self.scanerTextField.enabled = YES;
if (self.scanerTextField != nil && [self.scanerTextField canBecomeFirstResponder] && ![self.scanerTextField isFirstResponder]) {
[self.scanerTextField becomeFirstResponder];
}
}
else {
self.scanerTextField.enabled = NO;
}
}
目前测试并没发现什么其他问题。
|