gpt4 book ai didi

ios - 所以。我试图让我的文本字段下的字符数在屏幕上增加,但它没有增加

转载 作者:行者123 更新时间:2023-11-28 23:19:23 27 4
gpt4 key购买 nike

所以。我试图让我的文本字段下的字符数在屏幕上增加,但它没有增加。我一直在努力让它在过去的几个小时里工作,但似乎无法弄清楚。有什么方法可以让这项工作按照我想要的方式进行吗?还是因为我使用的是 TextFieldWrapperView 而无法正常工作?

import SwiftUI

struct ContentView: View {

@State var emojiText = ""


var body: some View {
VStack(spacing: 10) {
Text("Emoji Pad:")
.font(.body)
.foregroundColor(.gray)

TextFieldWrapperView(text: self.$emojiText)
.background(Color.gray)
.frame(width: 200, height: 50)
Text("\(emojiText.count)")
}
.frame(height: 40)
}
}


struct TextFieldWrapperView: UIViewRepresentable {

@Binding var text: String

func makeCoordinator() -> TFCoordinator {
TFCoordinator(self)
}
}

extension TextFieldWrapperView {


func makeUIView(context: UIViewRepresentableContext<TextFieldWrapperView>) -> UITextField {
let textField = EmojiTextField()
textField.delegate = context.coordinator
return textField
}


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

}
}

class TFCoordinator: NSObject, UITextFieldDelegate {
var parent: TextFieldWrapperView

init(_ textField: TextFieldWrapperView) {
self.parent = textField
}

// func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// if let value = textField.text {
// parent.text = value
// parent.onChange?(value)
// }
//
// return true
// }
}


class EmojiTextField: UITextField {

// required for iOS 13
override var textInputContextIdentifier: String? { "" } // return non-nil to show the Emoji keyboard ¯\_(ツ)_/¯

override var textInputMode: UITextInputMode? {
for mode in UITextInputMode.activeInputModes {
if mode.primaryLanguage == "emoji" {
return mode
}
}
return nil
}
}

struct EmojiTF_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

最佳答案

您在 UITextFieldDelegate 中留下了注释的代码,但这正是您所需要的。我更新了一点,因为当你从文本字段中删除文本时有错误。只需将您的 class TFCoordinator 替换为:

class TFCoordinator: NSObject, UITextFieldDelegate {
var parent: TextFieldWrapperView

init(_ textField: TextFieldWrapperView) {
self.parent = textField
}

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

if let value = textField.text, charIsBackSpace(string) {
let stringWithoutLastChar = value.dropLast()
parent.text = String(stringWithoutLastChar)
} else if let value = textField.text {
parent.text = value + string
} else {
parent.text = string
}

return true
}

private func charIsBackSpace(_ string: String) -> Bool {
guard let char = string.cString(using: String.Encoding.utf8) else { return false }
let charCode = strcmp(char, "\\b")
let backSpaceCode = -92
return charCode == backSpaceCode
}

}

关于ios - 所以。我试图让我的文本字段下的字符数在屏幕上增加,但它没有增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59889560/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com