面试题答案
一键面试具体方法和步骤
- 子类化UIView:创建UIView的子类,在该子类中重写触摸事件相关方法。
- 重写触摸事件方法:
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
:当触摸开始时调用。-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
:触摸移动时调用。-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
:触摸结束时调用。-(void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
:触摸取消时调用。
- 自定义响应链:可以通过重写
hitTest:withEvent:
方法来决定哪个视图应该响应触摸事件,改变默认的响应链查找逻辑。
涉及的类和方法
- 类:UIView及其子类。
- 方法:上述提到的触摸事件方法和
hitTest:withEvent:
方法。
需要注意的要点
- 调用super方法:在重写方法中,有时需要调用父类的相应方法以确保默认行为的正常执行,除非完全替代默认行为。
- 事件传递的准确性:在自定义
hitTest:withEvent:
方法时,要确保准确判断触摸点是否在视图范围内,避免错误的响应视图选择。 - 性能影响:复杂的自定义触摸逻辑可能会对性能产生影响,要注意优化代码。
举例说明
假设我们有一个自定义视图CustomView
继承自UIView,希望实现当手指在视图内移动时,视图跟随手指移动的效果。
#import "CustomView.h"
@implementation CustomView
-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self.superview];
self.center = currentPoint;
}
@end
在这个例子中,我们重写了touchesMoved:
方法,获取触摸点在父视图中的位置,并将当前视图的中心设置为该位置,从而实现了视图跟随手指移动的特定触摸交互逻辑。