日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

iOS13適配三指撤銷和文案限長實例詳解_IOS

作者:yuec ? 更新時間: 2023-03-25 編程語言

正文

在適配iOS13的過程中,UITextField輸入中文的時候三指撤銷產生了 crash。

Bugly報錯

NSInternalInconsistencyException
setGroupIdentifier:: _NSUndoStack 0x1206532f0 is in invalid state, calling setGroupIdentifier with no begin group mark

堆棧信息

 CoreFoundation	___exceptionPreprocess + 220
 libobjc.A.dylib	objc_exception_throw + 56
 Foundation	-[_NSUndoStack groupIdentifier]
 Foundation	-[NSUndoManager undoNestedGroup] + 240
 UIKitCore	-[UIUndoGestureInteraction undo:] + 72
 UIKitCore	-[UIKBUndoInteractionHUD performDelegateUndoAndUpdateHUDIfNeeded] + 96
 UIKitCore	-[UIKBUndoInteractionHUD controlActionUpInside:] + 152
 UIKitCore	-[UIApplication sendAction:to:from:forEvent:] + 96
 xxxxx	-[UIApplication(MemoryLeak) swizzled_sendAction:to:from:forEvent:] + 288
 UIKitCore	-[UIControl sendAction:to:forEvent:] + 240
 UIKitCore	-[UIControl _sendActionsForEvents:withEvent:] + 408
 UIKitCore	-[UIControl touchesEnded:withEvent:] + 520
 UIKitCore	-[UIWindow _sendTouchesForEvent:] + 2324
 UIKitCore	-[UIWindow sendEvent:] + 3352
 UIKitCore	-[UIApplication sendEvent:] + 336
 UIKitCore	___dispatchPreprocessedEventFromEventQueue + 5880
 UIKitCore	___handleEventQueueInternal + 4924
 UIKitCore	___handleHIDEventFetcherDrain + 108
 CoreFoundation	___CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24
 CoreFoundation	___CFRunLoopDoSource0 + 80
 CoreFoundation	___CFRunLoopDoSources0 + 180
 CoreFoundation	___CFRunLoopRun + 1080
 CoreFoundation	CFRunLoopRunSpecific + 464
 GraphicsServices	GSEventRunModal + 104
 UIKitCore	UIApplicationMain + 1936
 xxxxx	main + 148
 libdyld.dylib	_start + 4

問題定位

沒有太多思路的時候,通過注釋代碼,最終定位到了問題所在。

[self addTarget:observer
         action:@selector(textChange:)
forControlEvents:UIControlEventEditingChanged];
- (void)textChange:(UITextField *)textField {
    ... ... 
    UITextRange *selectedRange = [textField markedTextRange];
    if (!selectedRange || !selectedRange.start) {
        if (destText.length > maxLength) {
            textField.text = [destText substringToIndex:maxLength];
        }
    }
}

這段代碼在輸入的時候會限制文案的長度。三指撤銷會觸發UIControlEventEditingChanged事件,執行textChange,此時獲取到的markedTextRangenil,即便是存在markedText。這就導致UITextFieldtext有可能會被修改。修改文案后再繼續執行撤銷操作,必定會產生 crash。

解決方案

將文案判長和截取異步添加到主隊列,在下一個runloop執行。

- (void)textChange:(UITextField *)textField {
    dispatch_async(dispatch_get_main_queue(), ^{
        ... ...
    });
}

數字截斷后 crash

數字輸入限制長度后,超過長度后繼續輸入,這個時候撤銷也會產生crash,而且上面的方法不可行。目前想到的方案是在UITextField的回調方法進行輸入的攔截。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    /// 輸入數字后截取字符串仍舊可以觸發撤銷操作導致crash, 在這里攔截一下
    if (textField.keyboardType == UIKeyboardTypeNumberPad
        && range.location >= textField.tt_maxLength) {
            return NO;
    }
    return YES;
}

原文鏈接:https://juejin.cn/post/6844903952526344205

欄目分類
最近更新