
IOS
Swiftfunc hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView?参数point是触摸点的坐标,event是触发事件的UIEvent对象。返回值是一个UIView对象,表示响应事件的视图。如果没有找到合适的视图来处理事件,则返回nil。
Swiftfunc pointInside(_ point: CGPoint, with event: UIEvent?) -> Bool参数point是触摸点的坐标,event是触发事件的UIEvent对象。返回值是一个布尔值,表示给定点是否在视图的边界内。如果点在边界内,返回true;否则返回false。
Swiftclass CustomButton: UIButton { override func pointInside(_ point: CGPoint, with event: UIEvent?) -> Bool { let buttonBounds = self.bounds.insetBy(dx: -10, dy: -10) return buttonBounds.contAIns(point) }}let button = CustomButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))button.backgroundColor = UIColor.redbutton.setTitle("Click me", for: .normal)button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)view.addSubview(button)@objc func buttonTapped() { print("Button tapped")}在这个例子中,我们创建了一个自定义按钮CustomButton,重写了pointInside:withEvent:方法。在这个方法内部,我们将按钮的边界进行了缩小10个点,并判断触摸点是否在缩小后的边界内。如果在边界内,返回true;否则返回false。通过这种方式,我们可以自定义按钮的响应区域,使得只有按钮内的区域才能触发按钮的点击事件。hitTest:withEvent:和pointInside:withEvent:是IOS事件处理中非常重要的方法。它们通过判断触摸点是否在视图的边界内,确定最合适的视图来处理事件。通过重写pointInside:withEvent:方法,我们可以自定义视图的响应区域,实现更灵活的事件处理逻辑。希望本文对你理解这两个方法有所帮助。Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号