目前,当我在 UITextView 内部/外部单击时,我可以使键盘显示/隐藏。我想通过在键盘出现时将背景调暗,然后在键盘消失时使背景恢复正常来使效果更好。
我被告知这种行为可能被称为“焦点”或“模态阴影覆盖”,但一直无法找到符合我目标的教程或图像。 Here is a screenshot这正是我想要实现的目标:为新的 Instagram 帖子编写标题时,背景颜色变暗。
- 如何在 Swift 中实现此行为?
- 这种行为在 iOS 编程中被称为什么?
谢谢。 [:
最佳答案
首先回答你的两个问题:
实现叠加层的方法有很多种。
- 您可以添加 UIView 作为 subview ,为其提供约束作为与 textView 的垂直间距,并对齐 self.view 的底部,并在键盘按下时更改其 alpha提出/驳回。
- 您可以将 MaskView 添加到 View Controller 的 self.view 中。问题是,当应用蒙版时,它会将所有其他区域变成黑色(当然您可以更改颜色),并且只有您在蒙版框架中设置的部分才会是您建议的颜色(带有 0.5 alpha 的黑色)。
您可以将其称为添加覆盖层(除了我遇到的 Apple 文档中添加 mask 之外,没有其他方法)
现在来谈谈我长期以来一直使用的方法。
我向 ViewController 添加了一个名为 overlay 的 UIView 变量,当前将其框架设置为 CGRect.zero
var overlay: UIView = UIView(frame: CGRect.zero)
之后,我在 viewDidLoad 中添加 keyboardWillShow 和 keyboardWillHide 的通知观察器。
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
并添加相应的选择器来处理通知
@objc func keyboardWillShow(notification: NSNotification)
@objc func keyboardWillHide(notification: NSNotification)
在keyboardWillShow中,我获取键盘框架来获取键盘高度
之后,我通过获取屏幕的高度并减去导航栏高度、textView的高度和任何高度来计算叠加层的高度边距添加到textView的顶部
然后,我通过给定 textView 正下方的 Y 位置 来初始化我的 overlay 变量。最初,我将其颜色设置为 UIColor.clear 将其作为 subview 添加到 self.view,然后将其颜色更改为 0.5 alpha 的黑色,并使用 0.5 持续时间的动画。
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let overlayHeight = UIScreen.main.bounds.height - heightOfNavigationBar - keyboardSize.height - textView.frame.size.height - topConstraintofTextView(if any)
let overlayFrame = CGRect(x: 0, y: textView.frame.size.height + textView.frame.origin.y, width: UIScreen.main.bounds.width, height: overlayHeight)
self.overlay = UIView(frame: overlayFrame)
self.overlay.backgroundColor = .clear
self.view.addSubview(overlay)
UIView.animate(withDuration: 0.5, animations: {
self.overlay.backgroundColor = UIColor.black.withAlphaComponent(0.5)
})
}
}
之后,在keyboardWillHide中,我用一个小动画将叠加层的alpha更改为0,一旦结束,我就从superView中删除叠加层。
@objc func keyboardWillHide(notification: NSNotification) {
UIView.animate(withDuration: 0.5, animations: {
self.overlay.backgroundColor = UIColor.black.withAlphaComponent(0)
}, completion: { (completed) in
self.overlay.removeFromSuperview()
})
self.overlay.removeFromSuperview()
}
我在 viewController 的 touchesBegan 中执行 self.view.endEditing(true)
来关闭键盘,但这取决于你想如何关闭它。
这是它的样子
希望对你有帮助!
关于ios - 当用户单击 UITextView 并出现键盘时如何使背景变暗/着色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48970777/