UIWebView键盘的accessoryBar隐藏

当前越来越多的iOS应用开始使用html进行交互显示,却会发现在UIWebView弹出的键盘比UITextView的键盘多出了左右移动以及完成按钮,那么如何去掉这些我们并不需要的按钮呢?苹果官方并没有给出方法,所以我们只能够自己来解决。

webview_keyboard.png

对于不同的iOS版本,我们的处理方法也会不同,因为官方没有提供方法,所有的方法都是需要自己去发现和修改。这里只写出iOS7以上版本的方法:

func hideKeyBoard() -> Void {
        for window in UIApplication.sharedApplication().windows {
            if !window.isMemberOfClass(UIWindow.self) {
                let keyboardWindow = window
                if #available(iOS 9.0, *) {
                    self.removeAccessoryBarForiOS9(keyboardWindow as UIView)
                } else if #available(iOS 8.0, *) {
                    self.removeAccessoryBarForiOS8(keyboardWindow as UIView)
                } else {
                    self.removeAccessoryBarForiOS7(keyboardWindow as UIView)
                }
            }
        }
        if #available(iOS 9.0, *) {
            self.removeAccessoryBarForiOS9(UIApplication.sharedApplication().windows.last! as UIView)
        }
    }
    
    func removeAccessoryBarForiOS9(keyboardWindow:UIView) -> Void {
        for possibleFormView:UIView in keyboardWindow.subviews {
            if possibleFormView.isMemberOfClass(NSClassFromString("UIInputSetContainerView")!) {
                for subviewOfInputSetContainerView in possibleFormView.subviews {
                    if subviewOfInputSetContainerView.isMemberOfClass(NSClassFromString("UIInputSetHostView")!) {
                        for subviewOfInputSetHostView in subviewOfInputSetContainerView.subviews {
                            // 隐藏工具条NSClassFromString
                            if subviewOfInputSetHostView.isMemberOfClass(NSClassFromString("UIWebFormAccessory")!) {
                                subviewOfInputSetHostView.layer.opacity = 0
                                subviewOfInputSetHostView.frame = CGRectZero
                            } else if (subviewOfInputSetHostView.isMemberOfClass(NSClassFromString("_UIRemoteKeyboardPlaceholderView")!)) {
                                subviewOfInputSetHostView.layer.opacity = 0
                                subviewOfInputSetHostView.frame = CGRectZero
                                
                                // 这里使用了私有方法获取对应的accessorBar,然后进行隐藏
                                var accessory = subviewOfInputSetHostView.performSelector(Selector("placeheldView")).takeRetainedValue()
                                if accessory.isMemberOfClass(NSClassFromString("UIWebFormAccessory")!) {
                                    let accessory = accessory as! UIView
                                    accessory.layer.opacity = 0
                                    accessory.frame = CGRectZero
                                }
                                
                            }
                                // 键盘背景, UIKBInputBackdropView有两个只隐藏上面的
                            else if subviewOfInputSetHostView.isMemberOfClass(NSClassFromString("UIKBInputBackdropView")!) && subviewOfInputSetHostView.frame.size.height < 100 {
                                subviewOfInputSetHostView.layer.opacity = 0
                                subviewOfInputSetHostView.userInteractionEnabled = false
                            }
                        }
                    }
                }
            }
        }
    }
    
    func removeAccessoryBarForiOS8(keyboardWindow:UIView) -> Void {
        for possibleFormView:UIView in keyboardWindow.subviews {
            if possibleFormView.isMemberOfClass(NSClassFromString("UIInputSetContainerView")!) {
                for subviewOfInputSetContainerView in possibleFormView.subviews {
                    if subviewOfInputSetContainerView.isMemberOfClass(NSClassFromString("UIInputSetHostView")!) {
                        for subviewOfInputSetHostView in subviewOfInputSetContainerView.subviews {
                            // 隐藏工具条
                            if subviewOfInputSetHostView.isMemberOfClass(NSClassFromString("UIWebFormAccessory")!) {
                                subviewOfInputSetHostView.layer.opacity = 0
                                subviewOfInputSetHostView.frame = CGRectZero
                            }
                                // 键盘背景, UIKBInputBackdropView有两个只隐藏上面的
                            else if subviewOfInputSetHostView.isMemberOfClass(NSClassFromString("UIKBInputBackdropView")!) && subviewOfInputSetHostView.frame.size.height < 100 {
                                subviewOfInputSetHostView.layer.opacity = 0
                                subviewOfInputSetHostView.userInteractionEnabled = false
                            }
                        }
                    }
                }
            }
        }
    }
    
    func removeAccessoryBarForiOS7(keyboardWindow:UIView) -> Void {
        for possibleFormView:UIView in keyboardWindow.subviews {
            if possibleFormView.isMemberOfClass(NSClassFromString("UIPeripheralHostView")!) {
                for subviewOfPeripheralHostView in possibleFormView.subviews {
                    // 隐藏工具条
                    if subviewOfPeripheralHostView.isMemberOfClass(NSClassFromString("UIWebFormAccessory")!) {
                        subviewOfPeripheralHostView.layer.opacity = 0
                        subviewOfPeripheralHostView.frame = CGRectZero
                    }
                    // 键盘背景, UIKBInputBackdropView有两个只隐藏上面的
                    else if subviewOfPeripheralHostView.isMemberOfClass(NSClassFromString("UIKBInputBackdropView")!) && subviewOfPeripheralHostView.frame.size.height < 100 {
                        subviewOfPeripheralHostView.layer.opacity = 0
                        subviewOfPeripheralHostView.userInteractionEnabled = false
                    }
                }
            }
        }
    }

实际中,隐藏键盘accessory后的样子如下图:

webview_keyboard_hideaccessory.png

需要注意的是,在示例代码使用设置layer透明,frame为空来进行隐藏,而不使用removeFromSuperView,是因为使用了removeFromSuperView,在键盘重新布局时会导致crash。当然如果有朋友解决了crash,使用removeFromSuperView会更好。

附:

  1. 上面示例代码Github地址
  2. 使用removeFromSuperView产生crash的崩溃栈:
2016-07-06 14:10:32.018 WebViewKeyBoard[10846:930540] The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0x7f82a172d880 V:[_UIRemoteKeyboardPlaceholderView:0x7f82a14e7e30]-(0)-[_UIKBCompatInputView:0x7f82a16f9950]>
 When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView(UIConstraintBasedLayout) _viewHierarchyUnpreparedForConstraint:] to debug.
2016-07-06 14:10:32.018 WebViewKeyBoard[10846:930540] *** Assertion failure in -[UIInputSetHostView _layoutEngine_didAddLayoutConstraint:roundingAdjustment:mutuallyExclusiveConstraints:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3512.60.7/NSLayoutConstraint_UIKitAdditions.m:590
2016-07-06 14:10:32.025 WebViewKeyBoard[10846:930540] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Impossible to set up layout with view hierarchy unprepared for constraint.'
*** First throw call stack:
(
 0   CoreFoundation                      0x0000000105517d85 __exceptionPreprocess + 165
 1   libobjc.A.dylib                     0x00000001072bbdeb objc_exception_throw + 48
 2   CoreFoundation                      0x0000000105517bea +[NSException raise:format:arguments:] + 106
 3   Foundation                          0x0000000105968d5a -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 198
 4   UIKit                               0x0000000106626b99 __120-[UIView(UIConstraintBasedLayout) _layoutEngine_didAddLayoutConstraint:roundingAdjustment:mutuallyExclusiveConstraints:]_block_invoke_2 + 254
 5   UIKit                               0x000000010662698b -[UIView(UIConstraintBasedLayout) _layoutEngine_didAddLayoutConstraint:roundingAdjustment:mutuallyExclusiveConstraints:] + 385
 6   UIKit                               0x0000000106626e04 -[UIView(UIConstraintBasedLayout) _tryToAddConstraintWithoutUpdatingConstraintsArray:roundingAdjustment:mutuallyExclusiveConstraints:] + 65
 7   UIKit                               0x0000000106626f7d -[UIView(UIConstraintBasedLayout) _tryToAddConstraint:roundingAdjustment:mutuallyExclusiveConstraints:] + 288
 8   UIKit                               0x000000010662719f -[UIView(UIConstraintBasedLayout) _addConstraint:] + 274
 9   UIKit                               0x0000000106627438 __50-[UIView(UIConstraintBasedLayout) addConstraints:]_block_invoke + 197
 10  Foundation                          0x00000001058f23d3 -[NSISEngine withBehaviors:performModifications:] + 155
 11  UIKit                               0x0000000106626577 -[UIView(UIConstraintBasedLayout) _withAutomaticEngineOptimizationDisabled:] + 58
 12  UIKit                               0x0000000106627348 -[UIView(UIConstraintBasedLayout) addConstraints:] + 379
 13  UIKit                               0x00000001066b5531 -[UIInputWindowController updateViewConstraints] + 3558
 14  UIKit                               0x00000001066b1fde -[UIInputSetHostView _didChangeKeyplaneWithContext:] + 224
 15  UIKit                               0x000000010650f1cc -[_UIKBCompatInputView _didChangeKeyplaneWithContext:] + 87
 16  UIKit                               0x0000000106004397 -[UIKeyboard _didChangeKeyplaneWithContext:] + 324
 17  UIKit                               0x0000000105fe7b04 -[UIKeyboardImpl _didChangeKeyplaneWithContext:] + 1100
 18  UIKit                               0x000000010620d5a3 -[UIKeyboardLayoutStar(UIKeyboardLayoutJapanese50OnFlick) _didChangeKeyplaneWithContext:] + 183
 19  UIKit                               0x00000001061f121e -[UIKeyboardLayoutStar setKeyplaneName:] + 4512
 20  UIKit                               0x0000000106209c37 -[UIKeyboardLayoutStar setShift:] + 158
 21  UIKit                               0x0000000105fec46a -[UIKeyboardImpl notifyShiftState] + 73
 22  CoreFoundation                      0x000000010543cc37 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
 23  CoreFoundation                      0x000000010543cba7 __CFRunLoopDoObservers + 391
 24  CoreFoundation                      0x00000001054326c4 __CFRunLoopRun + 836
 25  CoreFoundation                      0x00000001054320f8 CFRunLoopRunSpecific + 488
 26  GraphicsServices                    0x0000000109badad2 GSEventRunModal + 161
 27  UIKit                               0x0000000105d3ff09 UIApplicationMain + 171
 28  WebViewKeyBoard                     0x000000010532a242 main + 114
 29  libdyld.dylib                       0x0000000107d7f92d start + 1
 30  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,478评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,825评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,482评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,726评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,633评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,018评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,513评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,168评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,320评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,264评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,288评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,995评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,587评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,667评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,909评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,284评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,862评论 2 339

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,977评论 4 60
  • 截止到2014年11月底,我第二次加入SGS (一家在瑞士苏黎士上市、股价达每股2000多法朗的全球最大的第三方检...
    格思阿甘阅读 2,228评论 21 10
  • 这是一个性向测试题。 如果你在ATM机上取款一千元,结果取款机却吐出来2000元。大致来说有几种处理方式,甲会取走...
    楚天阔阔阅读 247评论 0 0
  • 姓名:冉乔琪~公司:天兴医药 【日精进打卡第※113※天】 【知~学习】 《六项精进》2遍 共335遍 《大学》2...
    小小新酱阅读 162评论 0 0