QQ的输入界面实现了摇一摇能清空输入框功能,感觉很实用,然后就琢磨了一下实现思路。以下是自己的实现方法:
- 首先开启“摇一摇”的监听
[UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;
- 分别重写
- (void)motionBegan:(UIEventSubtype)motion withEvent:(nullable UIEvent *)event NS_AVAILABLE_IOS(3_0);//摇一摇开始
- (void)motionEnded:(UIEventSubtype)motion withEvent:(nullable UIEvent *)event NS_AVAILABLE_IOS(3_0);//摇一摇结束
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(nullable UIEvent *)event NS_AVAILABLE_IOS(3_0);//摇一摇退出
- 接着监听输入框文本的变化,当文本不为空的时候,摇一摇就弹出一个alert;为空的时候就不处理。
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
if (event.subtype == UIEventSubtypeMotionShake) { // 判断是否是摇动结束
if (_b) {
UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"是否撤销?" message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
self.textField.text = @"";
}];
UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[alertVC dismissViewControllerAnimated:YES completion:nil];
}];
[alertVC addAction:action1];
[alertVC addAction:action2];
[self presentViewController:alertVC animated:YES completion:nil];
}
}
}
完整的项目代码
#import "ViewController.h"
@interface ViewController (){
BOOL _b;
}
@property (weak, nonatomic) IBOutlet UITextField *textField;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_b = NO;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(change) name:UITextFieldTextDidChangeNotification object:self.textField];
//开启支持摇动
[UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;
}
//当输入框值发生变化的时候
- (void)change{
_b = self.textField.text.length > 0;
}
//摇动结束
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
if (event.subtype == UIEventSubtypeMotionShake) {
if (_b) {
UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"是否撤销?" message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
self.textField.text = @"";
}];
UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[alertVC dismissViewControllerAnimated:YES completion:nil];
}];
[alertVC addAction:action1];
[alertVC addAction:action2];
[self presentViewController:alertVC animated:YES completion:nil];
}
}
}
@end