草庐IT

iOS拖拽控件到UITextView进行复制粘贴奔溃

langkee 2023-03-28 原文

前言

iOS 15以后,我们可以通过拖拽一个控件(UITextFieldUITextView)的形式将其内容复制粘贴到另一个UITextView,在拖拽之前,如果UITextView的内容为空,例如:@""@" "(含空格),在设置代理- (void)textViewDidChange:(UITextView *)textView时,并且在代理中改变UITextView的内容后, 或者 - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text返回NO如果不做特殊处理的话,一定会发生奔溃!

主要奔溃信息是:NSInternalInconsistencyException: Invalid parameter not satisfying: pos

奔溃详情如下

CrashDoctor Diagnosis: Application threw exception NSInternalInconsistencyException: Invalid parameter not satisfying: pos
Thread 0 Crashed:
0   CoreFoundation                      0x00000001a8909d78 __exceptionPreprocess
1   libobjc.A.dylib                     0x00000001c156e734 objc_exception_throw
2   Foundation                          0x00000001aa18f1f0 _userInfoForFileAndLine
3   UIKitCore                           0x00000001abe850d4 -[_UITextKitTextPosition compare:]
4   UIKitCore                           0x00000001aad027d0 -[UITextInputController comparePosition:toPosition:]
5   UIKitCore                           0x00000001abe90a9c -[UITextView comparePosition:toPosition:]
6   UIKitCore                           0x00000001abe58dec -[UITextPasteController _clampRange:]
7   UIKitCore                           0x00000001abe595d8 __87-[UITextPasteController _performPasteOfAttributedString:toRange:forSession:completion:]_block_invoke
8   UIKitCore                           0x00000001abe597f0 __87-[UITextPasteController _performPasteOfAttributedString:toRange:forSession:completion:]_block_invoke.177
9   UIKitCore                           0x00000001abe81204 -[UITextInputController _pasteAttributedString:toRange:completion:]
10  UIKitCore                           0x00000001abe59524 -[UITextPasteController _performPasteOfAttributedString:toRange:forSession:completion:]
11  UIKitCore                           0x00000001abe587c4 __49-[UITextPasteController _executePasteForSession:]_block_invoke
12  libdispatch.dylib                   0x00000001a856ee68 _dispatch_call_block_and_release
13  libdispatch.dylib                   0x00000001a8570a2c _dispatch_client_callout
14  libdispatch.dylib                   0x00000001a857ef48 _dispatch_main_queue_drain
15  libdispatch.dylib                   0x00000001a857eb98 _dispatch_main_queue_callback_4CF
....................................................................

虽然这种情况很特殊,很少有用户去这样复制粘贴内容,但是一旦用户量大的话,或者用户总是使用这种方式去复制粘贴的话,奔溃的影响还是很大的。

例如,我们将第一个UITextView拖拽并复制内容Hello world到另一个UITextView,即发生奔溃,奔溃演示动画: 动画演示链接

环境

  • Xcode 13.2.1
  • iPhone 13 Pro Max(模拟器)
  • iOS 15.2
  • M1 macOS Monterey 12.2.1

代码重现

新建一个工程,代码如下

@interface ViewController ()<UITextViewDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(50, 100, 120, 50)];
    textView.text = @"Hello world";
    textView.backgroundColor = UIColor.greenColor;
    textView.font = [UIFont systemFontOfSize:19];
    [self.view addSubview:textView];
    
    UITextView *textView1 = [[UITextView alloc] initWithFrame:CGRectMake(50, 180, 250, 200)];
    textView1.delegate = self;
    textView1.backgroundColor = UIColor.cyanColor;
    [self.view addSubview:textView1];
}

// MARK: - UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView {
    textView.text = @"Hello";
}

@end

在上面的代码中,我们拖拽textView并复制其内容Hello worldtextView1,并在- (void)textViewDidChange:(UITextView *)textView中设置textView.text = @"Hello";,即改变textView1的内容。然后,运行项目,拖拽textViewtextView1,即发生奔溃。

解决

目前,可以有2种方案解决。

方案一(推荐)

对要复制到的UITextViewtextView1设置代理UITextPasteDelegate,如下

@interface ViewController ()<UITextViewDelegate, UITextPasteDelegate>

@end
 
textView1.pasteDelegate = self;

实现代理方法

// MARK: - UITextPasteDelegate

// Fix a crash where app will crash on iOS 15 or later if the user drags the UITextField or UITextView control to copy and paste.
- (UITextRange *)textPasteConfigurationSupporting:(id<UITextPasteConfigurationSupporting>)textPasteConfigurationSupporting
                   performPasteOfAttributedString:(NSAttributedString *)attributedString
                                          toRange:(UITextRange *)textRange {
    if ([textPasteConfigurationSupporting isKindOfClass:[UITextView class]]) {
        [(UITextView *)textPasteConfigurationSupporting replaceRange:textRange withText:attributedString.string];
    }
    return textRange;
}

在这个复制粘贴代理方法中,我们通过在复制粘贴的时候,对UITextView要复制粘贴的内容进行替换,就可以解决奔溃的问题。

方案二(不推荐)

方案一唯一不同的是代理方法中的处理方式

- (UITextRange *)textPasteConfigurationSupporting:(id<UITextPasteConfigurationSupporting>)textPasteConfigurationSupporting
                   performPasteOfAttributedString:(NSAttributedString *)attributedString
                                          toRange:(UITextRange *)textRange {
    if ([textPasteConfigurationSupporting isKindOfClass:[UITextView class]] && UIPasteboard.generalPasteboard.hasStrings) { 
        [(UITextView *)textPasteConfigurationSupporting insertText:UIPasteboard.generalPasteboard.string ?: @""];
    }
    return textRange;
}

不推荐方案二的原因是,虽然避免了奔溃,我们无法获取到被拖拽的控件textView中的内容,也就是即使我们拖拽textViewtextView1textView1的内容依旧不会变化。但是要特别注意,有一种情况会变化,如果我们在手机中的任何地方已经复制了文本,然后通过拖拽textViewtextView1textView1会获取到已经复制的文本!例如,我们已经在短信中复制了“好的”,然后在应用中拖拽textViewtextView1,如果textView的内容为空,textView1的内容就会变成“好的”,如果不为空,例如textView的内容为明白,,那么textView1的内容就会变成“明白,好的”也就是说,通过方案二,拖拽控件永远只是执行粘贴操作

注意:方案二需要用真机进行测试。

完整代码

@interface ViewController ()<UITextViewDelegate, UITextPasteDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(50, 100, 120, 50)];
    textView.text = @"Hello world";
    textView.backgroundColor = UIColor.greenColor;
    textView.font = [UIFont systemFontOfSize:19];
    [self.view addSubview:textView];
    
    UITextView *textView1 = [[UITextView alloc] initWithFrame:CGRectMake(50, 180, 250, 200)];
    textView1.delegate = self; 
    textView1.pasteDelegate = self;
    textView1.backgroundColor = UIColor.cyanColor;
    [self.view addSubview:textView1];
}

// MARK: - UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView {
    if (textView.text.length > 2) {
        textView.text = [textView.text substringFromIndex:2];
    } else {
        textView.text = @"";
    }
}

// MARK: - UITextPasteDelegate

//// Fix a crash where app will crash on iOS 15 or later if the user drags the UITextField or UITextView control to copy and paste.
- (UITextRange *)textPasteConfigurationSupporting:(id<UITextPasteConfigurationSupporting>)textPasteConfigurationSupporting
                   performPasteOfAttributedString:(NSAttributedString *)attributedString
                                          toRange:(UITextRange *)textRange {
    if ([textPasteConfigurationSupporting isKindOfClass:[UITextView class]]) {
        [(UITextView *)textPasteConfigurationSupporting replaceRange:textRange withText:attributedString.string];
    }
    return textRange;
}

/**
- (UITextRange *)textPasteConfigurationSupporting:(id<UITextPasteConfigurationSupporting>)textPasteConfigurationSupporting
                   performPasteOfAttributedString:(NSAttributedString *)attributedString
                                          toRange:(UITextRange *)textRange {
    if ([textPasteConfigurationSupporting isKindOfClass:[UITextView class]] && UIPasteboard.generalPasteboard.hasStrings) {
        [(UITextView *)textPasteConfigurationSupporting insertText:UIPasteboard.generalPasteboard.string ?: @""];
    }
    return textRange;
}
*/

@end

小结

  • 拖拽前,如果要复制的UITextView(这里textView1)内容不为空(含空格),如"a"、"123",无论是在- (void)textViewDidChange:(UITextView *)textView中改变内容或者- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text返回NO,一定不会奔溃。
  • 拖拽前,如果要复制的UITextView(这里textView1)内容为空(如""、" "),无论是在- (void)textViewDidChange:(UITextView *)textView中改变内容或者- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text返回NO,一定会奔溃。
  • 方案一和方案二都可以解决奔溃的问题,推荐方案一。

附录

有关iOS拖拽控件到UITextView进行复制粘贴奔溃的更多相关文章

  1. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  2. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  3. ruby - 使用 C 扩展开发 ruby​​gem 时,如何使用 Rspec 在本地进行测试? - 2

    我正在编写一个包含C扩展的gem。通常当我写一个gem时,我会遵循TDD的过程,我会写一个失败的规范,然后处理代码直到它通过,等等......在“ext/mygem/mygem.c”中我的C扩展和在gemspec的“扩展”中配置的有效extconf.rb,如何运行我的规范并仍然加载我的C扩展?当我更改C代码时,我需要采取哪些步骤来重新编译代码?这可能是个愚蠢的问题,但是从我的gem的开发源代码树中输入“bundleinstall”不会构建任何native扩展。当我手动运行rubyext/mygem/extconf.rb时,我确实得到了一个Makefile(在整个项目的根目录中),然后当

  4. ruby - 如何进行排列以有效地定制输出 - 2

    这是一道面试题,我没有答对,但还是很好奇怎么解。你有N个人的大家庭,分别是1,2,3,...,N岁。你想给你的大家庭拍张照片。所有的家庭成员都排成一排。“我是家里的friend,建议家庭成员安排如下:”1岁的家庭成员坐在这一排的最左边。每两个坐在一起的家庭成员的年龄相差不得超过2岁。输入:整数N,1≤N≤55。输出:摄影师可以拍摄的照片数量。示例->输入:4,输出:4符合条件的数组:[1,2,3,4][1,2,4,3][1,3,2,4][1,3,4,2]另一个例子:输入:5输出:6符合条件的数组:[1,2,3,4,5][1,2,3,5,4][1,2,4,3,5][1,2,4,5,3][

  5. ruby - 即使失败也继续进行多主机测试 - 2

    我已经构建了一些serverspec代码来在多个主机上运行一组测试。问题是当任何测试失败时,测试会在当前主机停止。即使测试失败,我也希望它继续在所有主机上运行。Rakefile:namespace:specdotask:all=>hosts.map{|h|'spec:'+h.split('.')[0]}hosts.eachdo|host|begindesc"Runserverspecto#{host}"RSpec::Core::RakeTask.new(host)do|t|ENV['TARGET_HOST']=hostt.pattern="spec/cfengine3/*_spec.r

  6. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  7. ruby - 是否可以覆盖 gemfile 进行本地开发? - 2

    我们的git存储库中目前有一个Gemfile。但是,有一个gem我只在我的环境中本地使用(我的团队不使用它)。为了使用它,我必须将它添加到我们的Gemfile中,但每次我checkout到我们的master/dev主分支时,由于与跟踪的gemfile冲突,我必须删除它。我想要的是类似Gemfile.local的东西,它将继承从Gemfile导入的gems,但也允许在那里导入新的gems以供使用只有我的机器。此文件将在.gitignore中被忽略。这可能吗? 最佳答案 设置BUNDLE_GEMFILE环境变量:BUNDLE_GEMFI

  8. ruby - 在 Windows 机器上使用 Ruby 进行开发是否会适得其反? - 2

    这似乎非常适得其反,因为太多的gem会在window上破裂。我一直在处理很多mysql和ruby​​-mysqlgem问题(gem本身发生段错误,一个名为UnixSocket的类显然在Windows机器上不能正常工作,等等)。我只是在浪费时间吗?我应该转向不同的脚本语言吗? 最佳答案 我在Windows上使用Ruby的经验很少,但是当我开始使用Ruby时,我是在Windows上,我的总体印象是它不是Windows原生系统。因此,在主要使用Windows多年之后,开始使用Ruby促使我切换回原来的系统Unix,这次是Linux。Rub

  9. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  10. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

随机推荐