用swift实现一个灰色的弹层,点击背景隐藏,点击子视图,走子视图的响应。如何实现。
import Foundation
import UIKit
class XYZPresentBackgroundView: UIView {
var animationDur: Double = 0.2 //default 0.2s
override init(frame: CGRect) {
var f = frame;
if f.size == CGSize.zero {
f = CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
}
super.init(frame: f)
self.backgroundColor = UIColor.init(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5)
let tab:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(tap(_:)))
tab.delegate = self
self.addGestureRecognizer(tab)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func tap(_ tap:UITapGestureRecognizer){
self.hidden()
}
func show() {
let size:CGSize = UIScreen.main.bounds.size
self.frame = CGRect.init(x: 0, y: size.height, width: size.width, height: size.height)
UIView.animate(withDuration: animationDur) {
self.frame = CGRect.init(x: 0, y: 0, width: size.width, height: size.height)
} completion: { (_ success:Bool) in
}
}
func hidden() {
UIView.animate(withDuration: animationDur) {
let size:CGSize = UIScreen.main.bounds.size
self.frame = CGRect.init(x: 0, y: size.height, width: size.width, height: size.height)
} completion: { (_ success:Bool) in
}
}
}
extension XYZPresentBackgroundView:UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
for view in self.subviews {
if touch.view == view {
return false
}
}
return true
}
}
网友评论