我目前正在为我的应用编写日历系统。
我已经使用创建的toogleCalendar()
函数通过UIButton显示/隐藏日历。
我想在显示日历时隐藏日历并 如果用户触摸其外部。
类似的东西:
如果我在日历之外单击,日历将消失。
我试图插入一个子视图并在其上添加GestureRecognizer,但是它不起作用。
您是否知道我该怎么做?
这是切换功能:
func toggleCalendar(){
if !calendarIsHidden {
calendarIsHidden = true
UIView.animate(withDuration: 0.2, animations: {
self.shadowCalendarView.transform = CGAffineTransform(scaleX: 0.95, y: 0.95)
self.shadowCalendarView.alpha = 0
}) { (finish) in
if finish {
self.shadowCalendarView.isHidden = self.calendarIsHidden
}
}
} else {
calendarIsHidden = false
self.shadowCalendarView.isHidden = self.calendarIsHidden
UIView.animate(withDuration: 0.2, animations: {
self.shadowCalendarView.transform = .identity
self.shadowCalendarView.alpha = 1
}) { (finish) in
// Nothing for now
}
}
}
答案 0 :(得分:2)
您看到打开子视图时屏幕如何模糊到更暗的颜色吗?您可以在日历下方添加具有0.5(例如)alpha值的黑色视图,并像这样向其中添加UIGestureTapRecognizer
(我想这就是shadowCalendarView
的目的吗?):
// Somewhere in the code, for example on viewDidLoad if its a UIViewController, or anywhere in your dismissal function:
shadowCalendarView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(yourClassName.handleDismiss)))
@objc func handleDismiss() {
// Dismisses the calendar with fade animation
UIView.animate(withDuration: 0.3, animations: {
self.calendarView.alpha = 0.0
self.shadowCalendarView.alpha = 0.0
}) { ( finished ) in
self.calendarView.isHidden = true
self.shadowCalendarView.isHidden = true
// If you are implementing calendar as a child view, remove it in the completion block of the animation like so:
self.willMove(toParentViewController: nil)
self.view.removeFromSuperview()
self.removeFromParentViewController()
}
}
如果此答案不够清楚,请尝试提供更多信息,我将尝试进行相应的编辑。例如实现,它是一个新的ViewController作为childView吗?它只是一个视图吗?
答案 1 :(得分:2)
在您的UITapGestureRecognizer
中添加一个self.view
,并在action
的构造函数的UITapGestureRecognizer
部分内,您将输入一个函数,在其中您将提供用于检查是否您的日历已显示/启用,并且可以进一步隐藏。
let mytapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
self.view.addGestureRecognizer(mytapGestureRecognizer)
self.isUserInteractionEnabled = true
func handleTap(_ sender:UITapGestureRecognizer){
if !calendarIsHidden {
calendarIsHidden = true
//Hide the calendar here
}
else {
calendarIsHidden = false
// Show the Calendar Here
}
}