在使用textInputAutocapitalization时,我在应用格式时遇到问题. 当我们取消textInputAutocapitalization 的注释时,它在iOS 17上工作正常,但对于iOS 16,当用户输入超过9个字母并提交时,什么都不会发生.你知道哪里可以发行吗?

这是我的代码

import SwiftUI

struct ContentView: View {
    @FocusState var isFocused: Bool
    let lengh = 9
    @State var text = ""
    var body: some View {
        VStack {
            HStack {
                TextField("write text here...",
                          value: $text,
                          format: .defaultUppercased)
                .focused($isFocused)
                //.textInputAutocapitalization(.characters)
            }
            .border(.black)
        }
        .padding()
        .onChange(of: text) {
            if text.count > lengh {
                text = String($0.prefix(lengh))
            }
        }
    }
}

#Preview {
    ContentView()
}

public struct DefaultUppercasedFormatStyle: ParseableFormatStyle {
    
    public init() {}
    
}

extension DefaultUppercasedFormatStyle {
    
    public var parseStrategy: Self {
        self
    }
    
    public func format(_ value: String) -> String {
        value
    }
    
}

extension DefaultUppercasedFormatStyle: ParseStrategy {
    
    public func parse(_ value: String) -> String {
        value.uppercased()
    }
    
}

extension FormatStyle where Self == DefaultUppercasedFormatStyle {
    
    public static var defaultUppercased: Self {
        Self()
    }
    
}

推荐答案

我最近在Stack Overflow上回答了一个类似的问题:Different behavior of FocusState on iOS 17. 罪魁祸首可能是FocusState,它在iOS 17之前存在错误.此外,甚至不可能使用在TextField构造函数中初始化绑定的解决方案,因为它在iOS 17上有相当多的问题.像这样的东西,我的意思是:

TextField("write text here...",
                      value: .init(get: {
                text
            }, set: { newVal in
                text = String(newVal.prefix(lengh))
            }),
                      format: .defaultUppercased)

这似乎在iOS 17上被打破了,这将是解决你的问题的一个很好的方法. 我脑海中唯一浮现的就是一个丑陋的变通方法.需要更改.onChange修改器,如下所示:

.onChange(of: text) {
        text = String($0.prefix(lengh))
        if #available(iOS 17, *) {
            return
        }
        guard text.count >= lengh else { return }
        isFocused = false
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
            isFocused = true
        }
    }

它将在iOS 17上运行得很好.副作用是,在iOS Pre 17上,它可以上下弹起键盘,但至少它将保留想要的行为.

让我知道如果这对你很好!

Swift相关问答推荐

我应该在自定义存储队列上使用弱self 吗?

UITableView未显示类数组数据

SwiftUI map 旋转

如何在SwiftUI中做出适当的曲线?

对实例方法appendInterpolation的调用没有完全匹配

如何通过 Enum 属性使用新的 #Predicate 宏获取

使第二个视图变灰 SwiftUI

有没有更快的方法来循环浏览 macOS 上已安装的应用程序?

如果 Swift 无法分配内存会怎样?

状态变量更改后,SwiftUI 视图不会更改

如何使用带有 span 样式标签的 Swift XMLParser

Alamofire 会自动存储 cookie 吗?

理解 Swift 2.2 Select 器语法 - #selector()

在 Swift 中强制崩溃的最简单方法

无法分配给属性:self 是不可变的,我知道如何修复但需要理解

Swift - 迭代 struct 对象时如何对其进行变异

如何以编程方式读取 wkwebview 的控制台日志(log)

如何发送静默推送通知有效负载

如何将多个枚举值作为函数参数传递

如何快速从另一个视图控制器重新加载表格视图