【问题标题】:Hiding a View after it was tapped点击后隐藏视图
【发布时间】:2018-07-25 18:52:34
【问题描述】:

我试图在点击后隐藏视图。为了做到这一点,我使用 touchesBegan 来检测视图是否被点击,如果是,它应该执行一个操作,例如隐藏视图和顶部的视图。定义了这两个视图:

   @IBOutlet weak var theDarkView: UIView!
@IBOutlet weak var theFinalView: UIView!

这是我想出的代码。

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        //-- hides the view whenever its touched
        if let touch = touches.first {
            if touch.view == self.theDarkView {
                if theDarkView.isHidden == false || theFinalView.isHidden == false {
                    theDarkView.isHidden = true
                    theFinalView.isHidden = true
                }
            } else {
                return
            }
        }
    }

如果你能帮助我并告诉我正确的方法来解决这个问题,并告诉我我在哪里搞砸了我的方法,那将不胜感激!

【问题讨论】:

  • 似乎有什么问题?
  • DarkView和FinalView存在于哪个视图中?
  • 您的代码有效。如果你触摸 theDarkView 设置隐藏到两个视图。
  • 你也想隐藏自己?
  • 当我按下视图时视图并没有隐藏,它们已连接到情节提要

标签: ios swift xcode view uiviewcontroller


【解决方案1】:

你的代码没问题,这也完成了同样的工作

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
     theDarkView.isHidden = touches.first?.view == self.theDarkView 
     theFinalView.isHidden = theDarkView.isHidden
}

【讨论】:

  • 我应该向 viewDidload 添加一些内容吗?我觉得我错过了一些连接 touchesBegan 方法的东西。我以前用过一次,它曾经可以工作,但我认为我缺少它的代码
  • touchesBegan 被免费调用,没有任何配置,如果您当前上传到 github 有问题,我认为这应该可以工作
【解决方案2】:

您的代码有效。当您点击 theDarkView 时,所有视图都设置为隐藏。

如果在您的项目中不起作用,则必须连接情节提要上的 IBOutlet。

编辑:

如果视图嵌入在滚动视图中,则它不起作用,因为 UIScrollView 拦截了这些触摸事件。

解决方案是 UIScrollView 的子类或使用 UITapGestureRecognizer 而不是 touchesBegan

一个可能的代码解决方案是在 viewDidLoad 中添加这个:

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapRecognized))
tapGesture.numberOfTapsRequired = 1
tapGesture.isEnabled = true
tapGesture.cancelsTouchesInView = false
theDarkView.addGestureRecognizer(tapGesture)

将 tapGesture 添加到您的视图,然后添加方法:

@objc func tapRecognized() {
    if red.isHidden == false || blue.isHidden == false {
        red.isHidden = true
        blue.isHidden = true
    }
}

【讨论】:

  • 我已经连接了屏幕,但点击后它们并没有隐藏
  • 如果您创建一个只有两个视图和您的代码的新项目视图,在点击 theDarkView 后它可以正常工作。只有一个问题:这些视图是免费的,还是嵌入在像 scrollView 或 tableView 这样拦截触摸的视图中?
  • 它们嵌入在滚动视图中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-04
相关资源
最近更新 更多