swift 如何更改单个文本字段的键盘语言?

nwlls2ji  于 12个月前  发布在  Swift
关注(0)|答案(2)|浏览(107)

我在我的视图中有几个文本字段,我想根据用户点击的文本字段更改键盘的语言。我知道我可以更改类型,如.numberPad,但如何更改语言?

wfsdck30

wfsdck301#

如果用户已经将语言添加到他的键盘上,您可以创建一个自定义文本字段并执行以下操作:
创建自定义文本域和文本域视图

import Foundation
import UIKit
import SwiftUI

class SpecificLanguageTextField: UITextField {
    
    var language: String? {
        didSet {
            if self.isFirstResponder{
                self.resignFirstResponder();
                self.becomeFirstResponder();
            }
        }
    }
    
    override var textInputMode: UITextInputMode? {
        if let language = self.language {
            for inputMode in UITextInputMode.activeInputModes {
                if let inputModeLanguage = inputMode.primaryLanguage, inputModeLanguage == language {
                    return inputMode
                }
            }
        }
        return super.textInputMode
    }
    
}

struct SpecificLanguageTextFieldView: UIViewRepresentable {

    let placeHolder: String
    var language: String = "en-US"
    @Binding var text: String

    func makeUIView(context: Context) -> UITextField{
        let textField = SpecificLanguageTextField(frame: .zero)
        textField.placeholder = self.placeHolder
        textField.text = self.text
        textField.language = self.language
        return textField
    }

    func updateUIView(_ uiView: UITextField, context: Context) {
    }

}

字符串
然后像这样使用它:

import SwiftUI

struct SpecificLanguageView: View {
    @State var text: String = ""
    var body: some View {
        SpecificLanguageTextFieldView(placeHolder: "test", language: "en-GB", text: $text)
    }
}

struct SpecificLanguageView_Previews: PreviewProvider {
    static var previews: some View {
        SpecificLanguageView()
    }
}

2ekbmq32

2ekbmq322#

尝试使用keyboardType =. alphabet。它将使键盘始终为英文,并禁止更改语言。它不会帮助每个人,但在我的情况下,不需要强制更改为其他语言-我们使用蓝牙扫描仪作为键盘。

相关问题