有谁知道当用户在 UITextView
中用两根手指点击时会调用什么方法?
当用户用两根手指点击时,会选择段落中的整个文本。我想以编程方式实现相同的选择,以使此段落选择在我的自定义单击手势方法中可用。
最佳答案
从 UITextView
双击手势识别器的默认行为来看,我认为 selectAll:
是被调用来处理文本选择的方法。同样,您可以通过在现有的 tapTextViewGesture:
方法中利用 selectAll:
来强制 TextView 在识别单击手势识别器时选择文本(如评论中所述) .
如果您希望文本选项像响应默认的双击手势识别器(即剪切、复制、粘贴等)一样自动显示,请将 selectAll:
设置为 self
:
- (IBAction)tapTextViewGesture:(id)sender {
[self.textView selectAll:self];
}
否则,要简单地选择文本而不显示菜单,请将其设置为nil
:
- (IBAction)tapTextViewGesture:(id)sender {
[self.textView selectAll:nil];
}
已更新
正如评论中的OP所指出的,UITextView
双击手势识别器最初只会导致选择单个段落。
首先,从当前光标位置显示编辑菜单:
// Access the application's shared menu
UIMenuController *menu = [UIMenuController sharedMenuController];
// Calculate the cursor's position within the superview
// and convert it to a CGRect
CGPoint cursorPosition = [self.textView caretRectForPosition:self.textView.selectedTextRange.start].origin;
CGPoint cursorPositionInView = [self.textView convertPoint:cursorPosition toView:self.view];
CGRect menuRect = CGRectMake(cursorPositionInView.x, cursorPositionInView.y, 0, 0);
// Show the menu from the cursor's position
[menu setTargetRect:menuRect inView:self.view];
[menu setMenuVisible:YES animated:YES];
然后选择当前段落,这是我的建议:
// Break the text into components separated by the newline character
NSArray *paragraphs = [self.textView.text componentsSeparatedByString:@"\n"];
// Keep a tally of the paragraph character count
int characterCount = 0;
// Go through each paragraph
for (NSString *paragraph in paragraphs) {
// If the total number of characters up to the end
// of the current paragraph is greater than or
// equal to the start of the textView's selected
// range, select the most recent paragraph and break
// from the loop
if (characterCount + paragraph.length >= self.textView.selectedRange.location) {
[self.textView setSelectedRange:NSMakeRange(characterCount, paragraph.length)];
break;
}
// Increment the character count by adding the current
// paragraph length + 1 to account for the newline character
characterCount += paragraph.length + 1;
}
关于ios - 模仿 UITextView 的默认双击行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27673065/