TextFieldTextView输入框键盘点击空白收起

一、普通View中点击空白处UITextField/UITextView键盘收起

@interface UIViewController (DismissKeyboard)
- (void)setupForDismissKeyboard;
@end
#import "UIViewController+DismissKeyboard.h"
@implementation UIViewController (DismissKeyboard)
- (void)setupForDismissKeyboard {
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer *singleTapGR =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(tapAnywhereToDismissKeyboard:)];
    __weak UIViewController *weakSelf = self;
    NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
    [nc addObserverForName:UIKeyboardWillShowNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [weakSelf.view addGestureRecognizer:singleTapGR];
                }];
    [nc addObserverForName:UIKeyboardWillHideNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [weakSelf.view removeGestureRecognizer:singleTapGR];
                }];
}
- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer {
    //endEditing会将self.view里所有的subview的first responder都resign掉
    [self.view endEditing:YES];
    //取消第一响应者,可取消所有控件的第一响应。
   //[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil]; 
}
@end

UITableView下Cell中添加TextField注意:textFieldShouldEndEditing不能返回return NO;否则键盘不关闭。
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField {
return YES;
}

二、键盘弹起后self.view上移,避免遮盖UITextField/UITextView

自定义键盘类

 //UIInputViewAudioFeedback协议模仿系统按键声音
public class WENumberKeyboardView: UIView, UIInputViewAudioFeedback {
    var array = ["1","2","3","4","5","6","7","8","9","00","0","11"]
    let keyPadding = 1.0 / UIScreen.mainScreen().scale
    let keyWidth = ceil((UIScreen.mainScreen().bounds.size.width - 4.0 / UIScreen.mainScreen().scale) / 3.0)
    let keyHeight: CGFloat = 53.0 //键盘高度可自己设定
    private weak var locationView: UIKeyInput?  //只要准许UIKeyInput协议,例如UITextField
    private var timer = NSTimer() 

    convenience init(locationView: UIKeyInput?) {
        self.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, ((53.0 + 1.0 / UIScreen.mainScreen().scale) * 4.0)))
        self.locationView = locationView
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.we_separatorColor()
        for i in 0 ... 2 {
            for j in 0...3 {
                let btn = UIButton()
                btn.frame = CGRectMake( CGFloat(i)  * (keyWidth + keyPadding) + keyPadding, CGFloat(j) * (keyHeight + keyPadding) + keyPadding, keyWidth, keyHeight)
                btn.tag = i + 3 * j
                btn.setTitle(array[btn.tag], forState: .Normal)
                btn.titleLabel?.font = UIFont.we_cnFont(24)
                btn.setTitleColor(UIColor.we_blackColor(), forState: .Normal)
                btn.we_setBackgroundColor(UIColor.whiteColor(), state: .Normal)
                btn.addTarget(self, action: #selector(WENumberKeyboardView.btnClick(_:)), forControlEvents: .TouchUpInside)
                if btn.tag == 11 {
                    btn.setTitle("", forState: .Normal)
                    btn.setImage(UIImage(named: "keyboardDelete"), forState: .Normal)
                    btn.addTarget(self, action: #selector(WENumberKeyboardView.btnClick(_:)), forControlEvents: .TouchDown)
                    //实现长按删除
                    let recongnizer = UILongPressGestureRecognizer(target: self, action:#selector(WENumberKeyboardView.longPressDeleteBackward(_:)))
                    btn.addGestureRecognizer(recongnizer) 
                }
                addSubview(btn)
            }
        }
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func btnClick(btn: UIButton) {
        UIDevice.currentDevice().playInputClick()
        if btn.tag == 11 {
            (locationView as? UITextField)?.deleteBackward()
        } else {
            (locationView as? UITextField)?.insertText(btn.titleLabel?.text  ?? "")
        }
    }
    //长按删除键执行方法,长按手势会返回开始和结束两个状态。
    func longPressDeleteBackward(sender: UILongPressGestureRecognizer)
    {
        if (sender.state == UIGestureRecognizerState.Began) {
            //延迟调用删除方法
            timer = NSTimer .scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(WENumberKeyboardView.changetext), userInfo: nil, repeats: true)
            timer .fire()
            
        }else if (sender.state == UIGestureRecognizerState.Ended){
            
            timer .invalidate()
            
        }
    }
    
    func changetext(){
        //删除字符操作
         (locationView as? UITextField)?.deleteBackward()
    }

}

VC中添加键盘

let keyView = WENumberKeyboardView(locationView: vc.textField)
vc.textField.inputView = keyView

显示和关闭键盘
[textField becomeFirstResponder];
[textField resignFirstResponder];

点击空白处隐藏键盘
[view endEditing:YES];可以让整个view取消第一响应者,从而让所有控件的键盘隐藏。

设置键盘类型
textView.keyboardType = UIKeyboardTypeDefault;
设置返回键类型
textView.returnKeyType = UIReturnKeyDefault;

自定义键盘
textView.inputView = newView;
textView.inputAccessoryView = newToolView;

UIButton长按事件实现方法
方法一
本文介绍方法
方法二
[btn addTarget:self action:@selector(offsetButtonTouchBegin:)forControlEvents:UIControlEventTouchDown];
[btn addTarget:self action:@selector(offsetButtonTouchEnd:)forControlEvents:UIControlEventTouchUpInside];
[btn addTarget:self action:@selector(offsetButtonTouchEnd:)forControlEvents:UIControlEventTouchUpOutside];

  • 自定义键盘处理textfield输入变化的问题
    正常情况UITextfield继承与UIControl,可以使用添加addTarget方法,来判断输入状态。
    [textField addTarget:self
    action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged]; //键盘未落下添加输入框内容发生改变时的事件处理,可用来对键盘输入的位数做限制。
  • (void)textFieldDidChange: (UITextField *)textField {
    NSLog(@"eventEditing%@",textField.text);
    }
    在自定义键盘情况下,并不会响应该addTarget方法,需要在键盘点击按钮的触发事件中添加事件调用。
    [textField sendActionsForControlEvents:UIControlEventEditingChanged];
    主要加法是:
    在自定义键盘页
    func btnClick(btn: UIButton) {
    let textField = locationView as? UITextField
    textField?.sendActionsForControlEvents(UIControlEvents.EditingChanged)
    }
    在VC的textfield上添加addTarget方法。

UITextField的小细节
http://www.cnblogs.com/wujy/p/5807073.html

UIView的Touch事件UIControlEvents详解http://blog.csdn.net/heng615975867/article/details/39321081

给键盘添加按键音
https://developer.apple.com/library/content/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/InputViews/InputViews.html

https://www.jianshu.com/p/cfb615a1275b

https://www.yuanmas.com/info/EkyQo9lMzv.html

https://www.jianshu.com/p/c446b4d10b73

https://www.cnblogs.com/galaxyyao/archive/2013/05/27/3102261.html

https://ask.csdn.net/questions/708986

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容