如何检测硬件键盘是否连接到iPhone?

时间:2010-07-01 15:28:11

标签: iphone ios

  

可能重复:
  iPad: detect if external keyboard is present

我一直在参考图书馆里挖掘,似乎无法在这里找到答案。

我假设某个地方有一些API我可以查询是否有外部硬件键盘正在使用中。

更新 我刚试过ExternalAccessory.framework中的EAAccessoryManager.connectedAccessories。这是不行,当启用硬件键盘时,它返回一个空数组。

1 个答案:

答案 0 :(得分:1)

我认为你必须使用以下代码 -

- (void)viewDidLoad {
    UIView*  _noExternalAccessoriesPosterView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [_noExternalAccessoriesPosterView setBackgroundColor:[UIColor whiteColor]];
    _noExternalAccessoriesLabelView = [[UILabel alloc] initWithFrame:CGRectMake(60, 170, 240, 50)];
    [_noExternalAccessoriesLabelView setText:@"No Accessories Connected"];
    [_noExternalAccessoriesPosterView addSubview:_noExternalAccessoriesLabelView];
    [[self view] addSubview:_noExternalAccessoriesPosterView];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_accessoryDidConnect:) name:EAAccessoryDidConnectNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_accessoryDidDisconnect:) name:EAAccessoryDidDisconnectNotification object:nil];
    [[EAAccessoryManager sharedAccessoryManager] registerForLocalNotifications];

    _eaSessionController = [EADSessionController sharedController];
    _accessoryList = [[NSMutableArray alloc] initWithArray:[[EAAccessoryManager sharedAccessoryManager] connectedAccessories]];

    [self setTitle:@"Accessories"];

    if ([_accessoryList count] == 0) {
        [_noExternalAccessoriesPosterView setHidden:NO];
    } else {
        [_noExternalAccessoriesPosterView setHidden:YES];
    }
}

- (void)_accessoryDidConnect:(NSNotification *)notification {
    EAAccessory *connectedAccessory = [[notification userInfo] objectForKey:EAAccessoryKey];
    [_accessoryList addObject:connectedAccessory];

    if ([_accessoryList count] == 0) {
        [_noExternalAccessoriesPosterView setHidden:NO];
    } else {
        [_noExternalAccessoriesPosterView setHidden:YES];
    }

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:([_accessoryList count] - 1) inSection:0];
    [[self tableView] insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}

希望这对您有用,并且记住您必须使用ExternalAccessory Framework来获取此代码。