前言
在日常开发过程中,难免都会遇到子控件超过父视图的情况。超出父视图的部分是不能响应点击事件,但是总有些情况需要我们让超出的部分响应点击事件,那么就需要用到convertPoint。
convertPoint相关的方法
- 转换像素点
// 将像素point由point所在视图转换到目标视图view中,返回在目标视图view中的像素值
- (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view;
// 将像素point从view中转换到当前视图中,返回在当前视图中的像素值
- (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view;
- 转换Rect
// 将rect由rect所在视图转换到目标视图view中,返回在目标视图view中的rect
- (CGRect)convertRect:(CGRect)rect toView:(UIView *)view;
// 将rect从view中转换到当前视图中,返回在当前视图中的rect
- (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view;
问题描述
一个自己定义View,这个View中有一个UIButton,但是这个UIButton超出父视图一部分。
红色的是父视图,绿色的是子视图,是一个按钮。部分超过了红色视图。
代码如下:
#import "TestView.h"
@implementation TestView
- (instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
self.backgroundColor = [UIColor redColor];
self.button = [[UIButton alloc]initWithFrame:CGRectMake(0, -40, frame.size.width, 80)];
self.button.backgroundColor = [UIColor greenColor];
[self addSubview:self.button];
[self.button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
self.clipsToBounds = NO;
}
return self;
}
- (void)buttonClick:(UIButton *)sender{
NSLog(@"有输出");
}
// 解决UIButton超出父视图不能响应问题
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
CGPoint newPoint = [self convertPoint:point toView:self.button];
if ([self.button pointInside:newPoint withEvent:event]) {
return self.button;
}
return [super hitTest:point withEvent:event];
}
解决方案
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
CGPoint newPoint = [self convertPoint:point toView:self.button];
if ([self.button pointInside:newPoint withEvent:event]) {
return self.button;
}
return [super hitTest:point withEvent:event];
}
如有疑问可以联系我。谢谢浏览本文章。