IOS开发之触摸背景关闭键盘的代码实现

时间:2022-01-02 16:26:41

直接上代码:

// 触摸背景,关闭键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
UIView *view = (UIView *)[touch view];
if (view == self.view) {
[weightTextField resignFirstResponder];
}
}

以上代码是在一个viewController里面,if语句中的判断self.view指的就是背景。

touchesBegan:withEvent:是声明在UIResponder中的一个函数,当一个或多个手指在view或者window上触摸时会调用该函数。默认没有做任何事情。这里重写它。