如何在不遮挡整个屏幕的情况下禁用桌面视图,就像在Whatsapp中一样?我们的想法是,当SearchBar
中的SearchController
仍为空时,tableview
会变暗。到SearchController
,默认情况下会遮挡整个屏幕。使用obscuresBackgroundDuringPresentation
,也会遮挡整个屏幕。
我正在使用Xcode 9.3 - Swift 4。
答案 0 :(得分:1)
试试这个解决方案
1)声明视图
let keyboardView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width , height: UIScreen.main.bounds.height))
2)添加通知观察者并在viewDidLoad
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()
})
}