触摸开始否定观点



我的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)
}
}

最新更新