ios - 警告 : "Modifying state during view update, this will cause undefined behavior." in UIViewRepresentable

标签 ios swiftui

所以我有一个 UIViewRepresentable 包装了一个 UITextField,并且在 textFieldshouldChangeCharactersInRange 方法期间收到此错误:

struct MyTextField: UIViewRepresentable {

    class Coordinator: NSObject, UITextFieldDelegate, ObservableObject {
    
        @Binding var text: String

        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            if let currentValue = textField.text as NSString? {
                let proposedValue = currentValue.replacingCharacters(in: range, with: string)
                text = proposedValue // Warning is thrown from here
            }
            return true
        }
    }
...

在此处更新绑定(bind)而不触发此警告的正确方法是什么?

最佳答案

更新下一个偶数循环,例如

DispatchQueue.main.async {
    text = proposedValue
}

关于ios - 警告 : "Modifying state during view update, this will cause undefined behavior." in UIViewRepresentable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71914728/

相关文章:

ios - Cocoapods 错误 : 'Unable to read the license file'

ios - Objective-C - NSArray 到具有多个定界符的 NSString

ios - 是否有修改器可以更改 SwiftUI Picker 的标签颜色?

swift - 如何使用 CGAffineTransform 将旋转角度的 anchor 更改为中心?

条件 subview 的 SwiftUI 转换

通过 iTunes 同步大型内部应用程序时 iOS 同步错误 0xE8000004

ios - UICollectionView 布局问题

ios - SwiftUI导航栏标题和项目在向​​后滑动失败时不会消失

ios - 使用 SwiftUI 发送电子邮件

javascript - iOS6 上的 onClick 事件问题