iOS 自定义view 是上面文字某区域有点击事件和点击背景效果


@interface HTXDyDetailCommentCell : UITableViewCell



@property (nonatomic,strong) HJContentTextView * speciaView;

  if (model.toMemberNick.length) {

        //回复评论人的时候

        

        

        NSString * string = [NSString stringWithFormat:@"回复%@%@",model.toMemberNick,strA];

        CGSize size = [string sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(IPHONE_WIDTH - _iconImgView.frame.origin.x - DY_IMG_WH - 6 - 50 * KSCALE_X, 100) lineBreakMode:NSLineBreakByWordWrapping];

        NSMutableString *text = [[NSMutableString alloc] initWithString:[NSString stringWithFormat:@"%@",string]];

        //赋值,这一步不可以少,specialSegments保存了查询到的结果

        _speciaView.specialSegments = _attributeTextmodel.specialSegments;

        //设置查询文本和查询的关键字

        _speciaView.tv.attributedText = [_attributeTextmodel hilightClickedText:text HightText:[NSString stringWithFormat:@"%@",model.toMemberNick] isComment:YES];

        _speciaView.frame = CGRectMake(_iconImgView.frame.origin.x + DY_IMG_WH + 6, 25, IPHONE_WIDTH - _iconImgView.frame.origin.x - DY_IMG_WH - 6 - 50 * KSCALE_X, size.height);

        

        

        

    }else{

        //别人评论我的时候

        CGSize size = [strA sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(IPHONE_WIDTH - _iconImgView.frame.origin.x - DY_IMG_WH - 6 - 50 * KSCALE_X, 100) lineBreakMode:NSLineBreakByWordWrapping];

        

        

        NSMutableString *text = [[NSMutableString alloc] initWithString:[NSString stringWithFormat:@"%@",strA]];

        //赋值,这一步不可以少,specialSegments保存了查询到的结果

        _speciaView.specialSegments = _attributeTextmodel.specialSegments;

        //设置查询文本和查询的关键字

        _speciaView.tv.attributedText = [_attributeTextmodel hilightClickedText:text HightText:[NSString stringWithFormat:@"%@",model.toMemberNick]isComment:YES];

        _speciaView.frame = CGRectMake(_iconImgView.frame.origin.x + DY_IMG_WH + 6, 25, IPHONE_WIDTH - _iconImgView.frame.origin.x - DY_IMG_WH - 6 - 50 * KSCALE_X, size.height);

        

        

        

    }



//

//  HJAttributeTextModel.h

//  HJLinkClickedLabel

//

//  Created by ZhaoHanjun on 16/1/27.

//  Copyright © 2016 https://github.com/CoderHJZhao. All rights reserved.

//


#import <Foundation/Foundation.h>

#import <UIKit/UIKit.h>

@interface HJAttributeTextModel : NSObject

@property (nonatomic, copy) NSString *text;

@property (nonatomic, assign) NSRange range;

@property (nonatomic, strong) NSMutableArray *specialSegments;

@property (nonatomic, strong) NSString *linkUrl;

@property (nonatomic, assign, getter=isSpecial) BOOL special;

@property (nonatomic, assign, getter=isEmotion) BOOL emotion;



- (NSMutableAttributedString *)hilightClickedText:(NSMutableString *)text HightText:(NSString *)hightText isComment:(BOOL)isCom;

@end




//

//  HJAttributeTextModel.m

//  HJLinkClickedLabel

//

//  Created by ZhaoHanjun on 16/1/27.

//  Copyright © 2016 https://github.com/CoderHJZhao. All rights reserved.

//


#import "HJAttributeTextModel.h"


// 获取16进制格式

#define kColorWithValue(value) \

[UIColor colorWithRed:((float)((value & 0xFF0000) >> 16)) / 255.0 \

green:((float)((value & 0xFF00) >> 8)) / 255.0 \

blue:((float)(value & 0xFF)) / 255.0 alpha:1.0]

@implementation HJAttributeTextModel


- (NSMutableArray *)specialSegments

{

    if (!_specialSegments) {

        _specialSegments  = [[NSMutableArray alloc] init];

        

    }

    return _specialSegments;

    

}


- (NSMutableAttributedString *)hilightClickedText:(NSMutableString *)text HightText:(NSString *)hightText isComment:(BOOL)isCom;

{

    [self.specialSegments removeAllObjects];

    NSMutableArray *parts = [NSMutableArray array];

    NSError *error = NULL;

//    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)" options:NSRegularExpressionCaseInsensitive error:&error];

    

     NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:[NSString stringWithFormat:@"%@",hightText] options:NSRegularExpressionCaseInsensitive error:&error];

    

    NSTextCheckingResult *urlResult = [regex firstMatchInString:text options:0 range:NSMakeRange(0, [text length])];

    

    if (urlResult) {

        self.linkUrl = [text substringWithRange:urlResult.range];

        [text replaceCharactersInRange:urlResult.range withString:hightText];

        

    }


    if ([text rangeOfString:hightText].location != NSNotFound) {

        HJAttributeTextModel *seg = [[HJAttributeTextModel alloc] init];

        seg.text = hightText;

        seg.range = [text rangeOfString:hightText];

        seg.special = YES;

        [parts addObject:seg];

    }


    

    

    

    

    NSMutableAttributedString *attributeText = [[NSMutableAttributedString alloc] initWithString:text];


    

    if (isCom) {

        

        [attributeText addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(0, text.length)];


        

    }else{

     

        [attributeText addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:28 * KSCALE_X] range:NSMakeRange(0, text.length)];


    }

    

    

    

    if ([text isEqualToString:@"这条评论已删除"]) {

        

        [attributeText addAttribute:NSForegroundColorAttributeName value:kColor(113, 113, 113) range:NSMakeRange(0, text.length)];


    }else{

    

        [attributeText addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, text.length)];


    }

    

    

    NSInteger cnt = parts.count;

    for (NSInteger i=0; i<cnt; i++) {

        HJAttributeTextModel *ts = parts[i];

        if (ts.special) {

            

            [attributeText addAttribute:NSForegroundColorAttributeName value:kColor(103, 119, 156) range:ts.range];

            //                _memberNickLab.font = [UIFont fontWithName:@"Helvetica-Bold" size:28 * KSCALE_X];

            if (isCom) {

                

                [attributeText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Helvetica-Bold" size:15] range:ts.range];


                

            }else{

                

                [attributeText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Helvetica-Bold" size:28 * KSCALE_X] range:ts.range];


            }

            

            

            

//            //生成富文本中的图片

//            NSTextAttachment *attch = [[NSTextAttachment alloc] init];

//            attch.image = [UIImage imageNamed:@"share"];

//            attch.bounds = CGRectMake(0, 0, 20, 20);

//            NSAttributedString *emotionStr = [NSAttributedString attributedStringWithAttachment:attch];

//            //插入图片

//            [attributeText insertAttributedString:emotionStr atIndex:ts.range.location];

            HJAttributeTextModel *spec = [[HJAttributeTextModel alloc] init];

            spec.text = ts.text;

            NSInteger loc = ts.range.location;

//            NSInteger len = ts.text.length + 1;

            NSInteger len = ts.text.length;

            spec.range = NSMakeRange(loc, len);

            [self.specialSegments addObject:spec];

            

        }

    }

    return attributeText;

}


@end



//

//  HJContentTextView.h

//  HJLinkClickedLabel

//

//  Created by ZhaoHanjun on 16/1/27.

//  Copyright © 2016 https://github.com/CoderHJZhao. All rights reserved.

//


#import <UIKit/UIKit.h>

#import "HJAttributeTextModel.h"

typedef void(^ClickedBlock)(NSInteger);

@interface HJContentTextView : UIView


@property (nonatomic, strong) NSArray *specialSegments;

@property (nonatomic, weak) UITextView *tv;

@property (nonatomic, copy) ClickedBlock clickedBlock;


@end


//

//  HJContentTextView.m

//  HJLinkClickedLabel

//

//  Created by ZhaoHanjun on 16/1/27.

//  Copyright © 2016 https://github.com/CoderHJZhao. All rights reserved.

//


#import "HJContentTextView.h"

#define kSelf_SelectedColor [UIColor colorWithWhite:0 alpha:0.4] //点击背景  颜色


static const NSInteger coverTag = 11;

@implementation HJContentTextView


- (instancetype) initWithFrame:(CGRect)frame

{

    if ([super initWithFrame:frame]) {

        UITextView *tv = [[UITextView alloc] init];

        tv.textContainerInset = UIEdgeInsetsZero;

        tv.textContainer.lineFragmentPadding = 0;

        tv.editable = NO;

        tv.scrollEnabled = NO;

        tv.userInteractionEnabled = NO;

        tv.backgroundColor = [UIColor clearColor];

//        tv.font = [UIFont systemFontOfSize:14 * KSCALE_X];


        

        [self addSubview:tv];

        _tv = tv;

        

        

        

    }

    return self;

}


- (void)layoutSubviews

{

    [super layoutSubviews];

    _tv.frame = self.bounds;

}


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

{

    CGPoint pt = [[touches anyObject] locationInView:self];

    BOOL selected = NO;

    for (HJAttributeTextModel *spec in self.specialSegments) {

        self.tv.selectedRange = spec.range;

        NSArray *rects = [self.tv selectionRectsForRange:self.tv.selectedTextRange];

        self.tv.selectedRange = NSMakeRange(0, 0);

        for (UITextSelectionRect *selectionRect in rects) {

            CGRect rect = selectionRect.rect;

            if (rect.size.width == 0 || rect.size.height == 0) continue;

            if (CGRectContainsPoint(rect, pt)) {

                selected = YES;

                break;

            }

        }

        if (selected) {

            //点击事件处理

            self.clickedBlock(self.tag);

            

            for (UITextSelectionRect *selectionRect in rects) {

                //                self.clickedBlock();

                CGRect rect = selectionRect.rect;

                if(rect.size.width == 0 || rect.size.height == 0) continue;

                UIView *cover = [[UIView alloc] initWithFrame:rect];

                cover.layer.cornerRadius = 5;

                cover.layer.shouldRasterize = YES;

                cover.backgroundColor = kSelf_SelectedColor;

                cover.alpha = 0.3;

                cover.tag = coverTag;

                [self.tv insertSubview:cover atIndex:0];

                

            }

            break;

        }

    }

}


- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

{

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        for (UIView *view in self.tv.subviews) {

            if (view.tag == coverTag) {

                [view removeFromSuperview];

                

                

            }

        }

    });

}


- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

{

    for (UIView *view in self.tv.subviews) {

        if (view.tag == 110) {

            [view removeFromSuperview];

            

        }

    }

}


- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event

{

    if ([self clickInside:point withEvent:event]) {

        return [super hitTest:point withEvent:event];

        

    }

    else

    {

        return nil;

    }

}




- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event

{

    return [self clickInside:point withEvent:event];

}


- (BOOL)clickInside:(CGPoint)point withEvent:(UIEvent *)event

{

    for (HJAttributeTextModel *spec in self.specialSegments) {

        self.tv.selectedRange = spec.range;

        NSArray *rects = [self.tv selectionRectsForRange:self.tv.selectedTextRange];

        self.tv.selectedRange = NSMakeRange(0, 0);

        for (UITextSelectionRect *selectionRect in rects) {

            CGRect rect = selectionRect.rect;

            if (rect.size.width == 0 || rect.size.height == 0) continue;

            if (CGRectContainsPoint(rect, point)) {

                return YES;

            }

            else

            {

                return NO;

            }

        }

    }

    return NO;

}


@end



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值