iOS中的键盘可以在Swift的任何地方触摸

时间:2014-06-13 01:33:56

标签: swift ios8

我知道要通过触摸Obj-C中的任何其他地方来关闭键盘,你必须写

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
if ([_answerField isFirstResponder] && [touch view] != _answerField) {
    [_answerField resignFirstResponder];
}
[super touchesBegan:touches withEvent:event];
}

但是你怎么用Swift做到这一点?

由于

2 个答案:

答案 0 :(得分:1)

这是翻译:

override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
    let touch = event.allTouches().anyObject() as UITouch
    if _answerField.isFirstResponder() && touch.view != _answerField {
        _answerField.resignFirstResponder()
    }
    super.touchesBegan(touches, withEvent: event)
}

我建议阅读Apple" The Swift Programming Language"预订并查看Apple的beta documentation涉及他们现有的API以及如何与他们互动。

答案 1 :(得分:0)

您可以尝试将UITapGestureRecognizer(带有self.view.endEditing(true))分配给父视图