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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM