【问题标题】:Is it safe to call stringByReplacingCharactersInRange in UITextView's delegate textView:shouldChangeTextInRange:replacementText:?在 UITextView 的委托 textView:shouldChangeTextInRange:replacementText: 中调用 stringByReplacingCharactersInRange 是否安全?
【发布时间】:2013-02-04 03:52:07
【问题描述】:

我基于 UITextView 实现了一个自定义的 textview,试图监听文本更改事件。所以我实现了 UITextView 的委托:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    //It crashes!
    NSString *result = [textView.text stringByReplacingCharactersInRange:range withString:text];

    return YES;
}

在 iOS 5 和 iOS 6 中,上面的代码可以正常工作。但在 iOS 4.3 中,它会崩溃,但 ***-[NSCFString replaceCharactersInRange:withString:]: Range or index out of bounds 除外。 我打印了在 iOS 4.3 中找到的所有变量值,有时范围确实超出了范围:textView.text.length 是 111,但 range113,0。我的代码有什么问题?谢谢!

【问题讨论】:

  • NSString *result = [[textView.text stringByReplacingCharactersInRange:range withString:text]copy];试试这个而不是 NSString *result = [textView.text stringByReplacingCharactersInRange:range withString:text];
  • @Sudha 谢谢!但它仍然崩溃。我认为崩溃来自Range or index out of bounds
  • 在新字符串中获取您的 textview.text 并将该字符串传递到您的结果字符串中......我试过这个,它工作得很好。
  • 您是否在项目中的任何位置手动调用textView:shouldChangeTextInRange:replacementText?这应该可以正常工作,除非使用不正确的参数手动调用它。
  • @lnafziger 感谢您的回复!是的,你是对的,我确实在我的代码中手动调用了textView:shouldChangeTextInRange:replacementText,但我忘记了我已经更改了代码中的范围。

标签: ios ios4 nsstring uitextview uitextviewdelegate


【解决方案1】:

这个方法在textview发生变化时自动调用,非常稳定。我的猜测(正如您在上面的评论中确认的那样)是您必须在代码中手动调用此方法,并提供不正确的范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-06
    • 2014-10-21
    • 2017-05-28
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    相关资源
    最近更新 更多