首页 > 解决方案 > SWIFT:触摸屏幕时未调用 touchesEnded

问题描述

所以我有一个名为 SettingsViewController 的 tableviewController,它有以下 touchesEnded 函数:

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    print("A")

    super.touchesEnded(touches, with: event)
    print("B")
    
    if let touch = touches.first {
        print("C")
        let touchLocation = touch.location(in: view)

        // 290 because the width of the view is 414, and the SettingsViewController width gets set to 0.7 * the view width in SlideInTransition.  0.7 * 414 is 289.8
        if touchLocation.x > 290 {
            dismiss(animated: true)
        }
    }
}

我做了 print 语句,看看它是否被调用,它不是。此视图控制器在自定义转换中呈现“菜单式”幻灯片。使用自定义转换显示的新 tablevc 的 UIView 的边界是否可能是问题所在?无论如何,我已经尝试实现 super.touchesEnded,或者添加所有覆盖触摸功能并在每次模拟时点击整个屏幕,但 touchesEnded 永远不会被调用。知道出了什么问题以及如何解决吗?谢谢

标签: iosswiftxcodeuitableviewtouches

解决方案


我猜你把touchesEnded()函数放在你的表视图控制器中......这是行不通的。表格视图本身正在消耗触摸。

这可能对你有用...

将此UITableView子类添加到您的项目中:

class TouchableTableView: UITableView {
    
    var callback: (() -> ())?
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("A")
        
        super.touchesEnded(touches, with: event)
        print("B")
        
        if let touch = touches.first {
            print("C")
            let touchLocation = touch.location(in: self)
            
            // not clear where you're trying to check for touch, so this may need to be changed
            
            // 290 because the width of the view is 414, and the SettingsViewController width gets set to 0.7 * the view width in SlideInTransition.  0.7 * 414 is 289.8
            if touchLocation.x > 290 {
                // this code is in a UITableView subclass,
                //  so we can't call dismiss() from here
                //dismiss(animated: true)

                // instead, we tell the Controller to take action
                callback?()
            }
        }
    }

}

然后,在 Storyboard 中,选择 Table View Controller 中的 Table View 并将其自定义类分配给TouchableTableView

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

现在,touchesEnded()将在自定义TouchableTableView类中调用(除非您点击单元格中的交互式 UI 元素,例如按钮)。

然后我们使用“回调”闭包告诉控制器触摸。因此,在您的 中UITableViewController,将其添加到viewDidLoad()

class ExampleTableViewController: UITableViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // we're in a UITableViewController,
        // so make sure the tableView is our TouchableTableView class
        // if it is, setup the closure
        if let tv = tableView as? TouchableTableView {
            tv.callback = {
                // here is where we would, for example, call dismiss()
                self.dismiss(animated: true, completion: nil)
            }
        }

    }

}   

推荐阅读