CoreText 图文混排之点击事件

2020-08-10  本文已影响0人  coder_feng

我们知道,CoreText是基于UIView去绘制的,那么既然有UIView,就肯定会有点击事件

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event方法

那么图文混排的点击事件如何实现呢?

通过touchBegan方法拿到当前点击到的点,然后通过坐标判断这个点是否在某段文字上,如果在触发对应事件

实现代码

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch * touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];
    CGRect imageFrmToScreen = [self convertRectFromLoc:_imgFrm];
    if (CGRectContainsPoint(imageFrmToScreen, location)) {
        [[[UIAlertView alloc] initWithTitle:nil message:@"你点击了图片" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil] show];
        return;
    }
    [arrText enumerateObjectsUsingBlock:^(NSValue * rectV, NSUInteger idx, BOOL * _Nonnull stop) {
        CGRect textFrmToScreen = [self convertRectFromLoc:[rectV CGRectValue]];
        if (CGRectContainsPoint(textFrmToScreen, location)) {
            [self click];
            *stop = YES;
        }
    }];
    
}

///将系统坐标转换为屏幕坐标
-(CGRect)convertRectFromLoc:(CGRect)rect
{
    return CGRectMake(rect.origin.x, self.bounds.size.height - rect.origin.y - rect.size.height, rect.size.width, rect.size.height);
}

这里如果看的不够明白的话,可以去到上一篇看CoreText图文混排,这篇只要是为了说点击事件,所以直接从touchBegain这个方法入手即可,从代码中可以看到响应事件的优先级明显是要高于文字的,这个看事情情况的,如果觉得图片优先级高的情况下可以减少很多计算量,提高运行效率,就先设置图片的优先级,否则就设置文字。

大致逻辑

touchesBegan事件给我们提供了touches这么一个集合。里面装满了UITouch对象。

因为集合是无序的,所以我们通过anyObject取出其中的一个UITouch对象

 UITouch * touch = [touches anyObject];
 CGPoint location = [touch locationInView:self];
///将系统坐标转换为屏幕坐标
-(CGRect)convertRectFromLoc:(CGRect)rect
{
    return CGRectMake(rect.origin.x, self.bounds.size.height - rect.origin.y - rect.size.height, rect.size.width, rect.size.height);
}

if (CGRectContainsPoint(imageFrmToScreen, location)) {
        [[[UIAlertView alloc] initWithTitle:nil message:@"你点击了图片" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil] show];
        return;
    }

if (CGRectContainsPoint(imageFrmToScreen, location)) {
        [[[UIAlertView alloc] initWithTitle:nil message:@"你点击了图片" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil] show];
        return;
    }

上一篇 下一篇

猜你喜欢

热点阅读