iOS UITextView点击事件处理

自定义一个UITextView

UITextView 的selectedRange 影响 selectedTextRange 改变前者可影响后者

self.selectedRange -->self.selectedTextRange

@implementation HWStatusTextView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.editable = NO;
    //改变文字内边距 self.textContainerInset
= UIEdgeInsetsMake(0, -5, 0, -5); // 禁止滚动, 让文字完全显示出来 self.scrollEnabled = NO; } return self; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { // 触摸对象 UITouch *touch = [touches anyObject]; // 触摸点 CGPoint point = [touch locationInView:self]; NSArray *specials = [self.attributedText attribute:@"specials" atIndex:0 effectiveRange:NULL]; BOOL contains = NO; for (HWSpecial *special in specials) { self.selectedRange = special.range; // self.selectedRange --影响--> self.selectedTextRange // 获得选中范围的矩形框 NSArray *rects = [self selectionRectsForRange:self.selectedTextRange]; // 清空选中范围 self.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)) { // 点中了某个特殊字符串 contains = YES; break; } } if (contains) { for (UITextSelectionRect *selectionRect in rects) { CGRect rect = selectionRect.rect; if (rect.size.width == 0 || rect.size.height == 0) continue; UIView *cover = [[UIView alloc] init]; cover.backgroundColor = [UIColor greenColor]; cover.frame = rect; cover.tag = HWStatusTextViewCoverTag; cover.layer.cornerRadius = 5; [self insertSubview:cover atIndex:0]; } break; } } // 在被触摸的特殊字符串后面显示一段高亮的背景 } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self touchesCancelled:touches withEvent:event]; }); } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { // 去掉特殊字符串后面的高亮背景 for (UIView *child in self.subviews) { if (child.tag == HWStatusTextViewCoverTag) [child removeFromSuperview]; } } @end

 

转载于:https://www.cnblogs.com/code-changeworld/p/4713395.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值