iOS 根据当前触摸的位置显示出该位置的单词

#import "OXTouchTextView.h"

@implementation OXTouchTextView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.editable = NO;
    }
    
    return self;
}



- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    //No.1
    //开始写代码,触摸操作开始时,获取当前触摸位置的字符所属的单词。并用UIAlertView显示出来(提示:触摸位置需向下调整10个点,以便与文本元素对齐)
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self];
    touchPoint.y -= 10;
    
    NSInteger characterIndex = [self.layoutManager characterIndexForPoint:touchPoint inTextContainer:self.textContainer fractionOfDistanceBetweenInsertionPoints:NULL];
    
    if (characterIndex < self.text.length) {
        NSString *s=[self.text substringWithRange:NSMakeRange(characterIndex, 1)];
        NSLog(@"%@",s);
        //显示位置
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"点击的文字是" message:s preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [alertVC dismissViewControllerAnimated:YES completion:nil];
        }];
        [alertVC addAction:action];
        
        [self.vc presentViewController:alertVC animated:YES completion:nil];
    }

    
    //end_code
    [super touchesBegan: touches withEvent: event];
}


你可能感兴趣的:(IOS开发日志)