From f879291f16d291c854e01154d8b7fa9a29a33a44 Mon Sep 17 00:00:00 2001 From: Michael Kirk Date: Fri, 13 Apr 2018 17:56:27 -0400 Subject: [PATCH] Don't underestimate removed space. // FREEBIE --- .../attachments/AttachmentApprovalViewController.swift | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/SignalMessaging/attachments/AttachmentApprovalViewController.swift b/SignalMessaging/attachments/AttachmentApprovalViewController.swift index e7aa712e1..e869c0175 100644 --- a/SignalMessaging/attachments/AttachmentApprovalViewController.swift +++ b/SignalMessaging/attachments/AttachmentApprovalViewController.swift @@ -641,9 +641,15 @@ class CaptioningToolbar: UIView, UITextViewDelegate { Logger.debug("\(self.logTag) in \(#function) long text was truncated") self.lengthLimitLabel.isHidden = false + // `range` represents the section of the existing text we will replace. We can re-use that space. + // Range is in units of NSStrings's standard UTF-16 characters. Since some of those chars could be + // represented as single bytes in utf-8, while others may be 8 or more, the only way to be sure is + // to just measure the utf8 encoded bytes of the replaced substring. + let bytesAfterDelete: Int = (existingText as NSString).replacingCharacters(in: range, with: "").utf8.count + // Accept as much of the input as we can - let byteBudget = kOversizeTextMessageSizeThreshold + range.length - existingText.utf8.count - if byteBudget >= 0, let acceptableNewText = text.truncated(toByteCount: byteBudget) { + let byteBudget: Int = Int(kOversizeTextMessageSizeThreshold) - bytesAfterDelete + if byteBudget >= 0, let acceptableNewText = text.truncated(toByteCount: UInt(byteBudget)) { textView.text = (existingText as NSString).replacingCharacters(in: range, with: acceptableNewText) }