2016-08-22 46 views
1

我使用的是tabview,它工作正常,但如果我通過點擊任何地方tabbar停止工作,但所有其他按鈕的工作,添加解除鍵盤的代碼。這裏是我用來消除鍵盤代碼:用tabbar解析鍵盤

extension UIViewController { 
func hideKeyboardWhenTappedAround() { 
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard)) 
    view.addGestureRecognizer(tap) 
} 

func dismissKeyboard() { 
    view.endEditing(true) 
} 

}

回答

0

我不知道這是處理這一目標的最佳方式,但沒有experiementing,這似乎是唯一的萬無一失的方法,我瞭解。這將創建一個不可見的視圖,以識別點擊並在點擊後自行刪除。

class ThisViewController: UITableViewDelegate, UITableViewDatasource { 

    var tapView: ClickThroughView? 

    override func viewDidAppear(animated: Bool) { 
     super.viewDidAppear(animated) 
     NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.keyboardWillShow), name: UIKeyboardWillShowNotification, object: nil) 
     NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.keyboardWillHide), name: UIKeyboardWillHideNotification, object: nil) 
    } 

    func keyboardWillShow(notification: NSNotification) { 
     tapView = ClickThroughView(frame: view.frame) 
     tapView?.delegate = self 
     view.addSubview(tapView!) 
     view.bringSubviewToFront(tapView!) 
    } 

    func keyboardWillHide() { 
    } 

    deinit { 
     NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) 
     NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) 
    } 
} 

extension ThisViewController: HandleViewTapDelegate { 
    func handleTap() { 

     //code on tap not on keyboard 
     view.endEditing(true) 

     tapView?.removeFromSuperview() 
     tapView = nil 
    } 
} 

protocol HandleViewTapDelegate { 
    func handleTap() 
} 

class ClickThroughView: UIView { 
    var delegate: HandleViewTapDelegate? 

    override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool { 
     delegate?.handleTap() 
     return false 
    } 
} 
0

我固定它把在背景上按鈕,使該按鈕呼叫view.endEditing(true) 它是不是最漂亮的修復作用,但它的工作原理