touchesBegan 关闭视图

touchesBegan to dismiss view

我的 ViewController 中有一个视图从底部到中间占据了屏幕的一半。如果在视图内部以外的其他地方点击,我正在使用 touchesBegan 函数关闭视图,一切正常,除了当我触摸视图顶部的 10% 时,它会在不应该关闭时关闭,因为触摸仍在内部允许观看。

这是我用来呈现 vc:

的代码
            guard let vc = storyboard?.instantiateViewController(withIdentifier: "editvc") as? EditTodoViewController else {return}
                vc.modalPresentationStyle = .custom
                present(vc, animated: true)

这是我在里面的函数 vc:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first
    if touch != viewForVc {
        EditTodoViewController.textFromCellForTodo = ""
        dismiss(animated: true)
    }
}

你应该检查触摸是否不在视图中而不是检查不同

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first!
    let location = touch.location(in: self.view)
    
    if (!viewForVc.bounds.contains(location)) {
        EditTodoViewController.textFromCellForTodo = ""
        dismiss(animated: true)
    }
}

--- 编辑----

如果您想在检查包含之前以编程方式更改框架,请检查下面的代码

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first!
        let location = touch.location(in: self.view)
        
        // get the frame of view + 10% height
        let viewFrame = CGRect(origin: viewForVc.frame.origin, size: CGSize(width: viewForVc.frame.size.width, height: viewForVc.frame.size.height * 1.1))
        
        if (!viewFrame.contains(location)) {
            EditTodoViewController.textFromCellForTodo = ""
            dismiss(animated: true)
        }
    }