gpt4 book ai didi

ios - 使用 UITextPosition,从 textInRange 中获取前一个字符

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:46:10 28 4
gpt4 key购买 nike

我一直在上下搜索,但不知道该怎么做。假设我有一个这样的字符串:

NSString *string = @"&foo !foo";

我想要做的是区分 TextView 中的两个 foo(听起来很有趣哈哈)。当我点击一个时,我想知道哪个(& 或!)出现在它之前。我是这样理解的:

UITapGestureRecognizer *recognizer = (UITapGestureRecognizer *)sender;
UITextView *TV = (UITextView*)recognizer.view;
CGPoint location = [recognizer locationInView:TV];
location.y += TV.contentOffset.y;
UITextPosition *tapPosition = [TV closestPositionToPoint:CGPointMake(location.x, location.y)];
UITextRange *textRange = [TV.tokenizer rangeEnclosingPosition:tapPosition
withGranularity:UITextGranularityWord inDirection:UITextLayoutDirectionRight];
NSString *tappedWord = [TV textInRange:textRange];

我不知道如何获取前一个字符。 TV.tokenizer UITextGranularityCharacter 只获取最接近的字母,而不是符号。对此有什么解决方案吗?

最佳答案

检查:Convert selectedTextRange UITextRange to NSRange将您的 UITextRange 转换为 NSRange(我称之为 selectedRange)。

用之前对链接问题的回答启发我,您需要在代码末尾添加:

UITextPosition *beginning = TV.beginningOfDocument;
UITextPosition *selectionStart = textRange.start;
UITextPosition *selectionEnd = textRange.end;
NSInteger location = [TV offsetFromPosition:beginning toPosition:selectionStart];
NSInteger length = [TV offsetFromPosition:selectionStart toPosition:selectionEnd];
NSRange selectedRange = NSMakeRange(location,lenght);
NSRange range = NSMakeRange(selectedRange.location-1,1) //Maybe need to check if selectedRange.location>0
NSString *yourCharString = [[TV text] substringWithRange:range];

关于ios - 使用 UITextPosition,从 textInRange 中获取前一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23607883/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com