ios - Swift - 如果在 View 外部触摸则隐藏 View

标签 ios swift swift3 touch uigesturerecognizer

我目前正在为我的应用编写日历系统。 我已经使用 UIButton 和我创建的 toogleCalendar() 函数显示/隐藏日历。

I would like to hide the Calendar when the calendar is displayed and if the user touch outside of it.

类似的东西:

enter image description here

如果我点击日历以外的地方,日历就会消失。

我试图插入一个 subview 并在其上添加一个 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
         }

      }

}

最佳答案

UITapGestureRecognizer 添加到您的 self.viewUITapGestureRecognizer 构造函数的 action 部分中将输入一个函数,您将在其中呈现用于检查您的日历是否呈现/启用并可以进一步隐藏它的逻辑。

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
  }

}

关于ios - Swift - 如果在 View 外部触摸则隐藏 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52716543/

相关文章:

ios - 如何在 CFQuery TableViewController 中为 tableView 设置背景图片

ios - 如何使按钮在 UIScrollView 内滚动?

ios - SceneKit——平移手势移动节点太快

ios - Xcodebuild 因 cordova ios 项目而停止

ios - TableView限制使用(Swift)

ios - UIBezierPath行程不完整

swift3 - 在我的应用程序中单击按钮时打开手机设置

ios - 2017/Swift 3.1 - GCD 与 NSOperation

ios - Swift 在只有括号的行上崩溃

ios - 我应该从 iOS 上的 Realm 中删除旧表吗?