gpt4 book ai didi

ios - 模仿 UITextView 的默认双击行为

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

有谁知道当用户在 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/

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