如何在不像Whatsapp那样遮挡整个屏幕的情况下禁用tableview?其思想是当SearchBar
中的SearchController
仍然为空时,tableview
将变暗。若要SearchController
,默认情况下会遮挡整个屏幕。使用obscuresBackgroundDuringPresentation
,也会遮挡整个屏幕。
我用的是Xcode 9.3-Swift 4。
最佳答案
试试这个办法
1)声明视图
let keyboardView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width , height: UIScreen.main.bounds.height))
2)添加通知观察者并在
viewDidLoad
中查看颜色alpha keyboardView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
2)删除通知观察员使用
deinit {
NotificationCenter.default.removeObserver(self)
}
3)为视图添加约束
func addConstraints() {
view.addConstraint(NSLayoutConstraint(item: keyboardView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: keyboardView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: keyboardView, attribute: .top, relatedBy: .equal, toItem: self.view.safeAreaLayoutGuide, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: keyboardView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute,multiplier: 1, constant: UIScreen.main.bounds.height))
}
4)添加键盘显示和隐藏方法
@objc func keyboardWillShow(notification: NSNotification) {
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.storeCollectionView.addSubview(self.keyboardView)
self.addConstraints()
})
}
@objc func keyboardWillHide(notification: NSNotification) {
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.keyboardView.removeFromSuperview()
})
}