gpt4 book ai didi

ios - 编辑时UITextField自定义背景色

转载 作者:行者123 更新时间:2023-12-01 15:46:42 29 4
gpt4 key购买 nike

我正在尝试使用 SwiftUI 为 UITextField 提供背景颜色,因为我正在尝试在我的应用中使用一些独特的颜色来支持 LightMode 和 DarkMode。

我的颜色总是在 xcassets 文件夹中定义为 ColorSet,这是我最初用来实现这种背景颜色的代码。

TextField("Exam title", text: $title)
.padding()
.background(Color("cardBackground"))
.cornerRadius(8)

这样我就可以在不使用时更改 TextField 的背景颜色。结果是这样

Correct Look

我面临的问题是,只要我点击 TextField,它就会恢复为默认颜色(我认为这是默认颜色),而且我无法更改它。

When editing

所以我所做的是创建 TextField 的 UIViewRepresentable 实现,也许这对我的帮助比 SwiftUI 在这个阶段所能做的要多得多。

struct CustomUIKitTextField: UIViewRepresentable {

@Binding var text: String
var placeholder: String
var backgroundColor: UIColor = .red

func makeUIView(context: UIViewRepresentableContext<CustomUIKitTextField>) -> UITextField {
let textField = UITextField(frame: .zero)
textField.delegate = context.coordinator
textField.placeholder = placeholder
textField.backgroundColor = backgroundColor
return textField
}

func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<CustomUIKitTextField>) {
uiView.text = text
uiView.backgroundColor = backgroundColor
uiView.setContentHuggingPriority(.defaultHigh, for: .vertical)
uiView.setContentCompressionResistancePriority(.required, for: .vertical)
}

func makeCoordinator() -> CustomUIKitTextField.Coordinator {
Coordinator(parent: self)
}

class Coordinator: NSObject, UITextFieldDelegate {
var parent: CustomUIKitTextField

init(parent: CustomUIKitTextField) {
self.parent = parent
}

func textFieldDidChangeSelection(_ textField: UITextField) {
parent.text = textField.text ?? ""
}

func textFieldDidBeginEditing(_ textField: UITextField) {
print("Begin editing")
textField.backgroundColor = .brown
}

func textFieldDidEndEditing(_ textField: UITextField) {
print("Finished Editing")
}

}
}

如您所见,我已经尝试了一些东西(有些东西只是调试东西)但我在 UIKit 方面经验不多,所以我真的不知道解决这个问题的最佳方法是什么这类问题不多。

你以前遇到过类似的事情吗?我该如何解决这个问题?

编辑:

如果这有帮助的话,这是当 TextField 处于编辑模式时的 View 层次结构,并且将其自身放在 TextField 前面的选定元素是一个 UIFieldEditor

UIFieldEditor

最佳答案

首先,不要在 SwiftUI 中定义背景颜色:
.background(Color("cardBackground"))/去掉这行代码

在 makeUIView 方法中,设置默认背景颜色,当用户没有点击文本框时使用:

textfield.backgroundColor = .systemGray

最后,在 Coordinator 类中使用这些方法来控制背景颜色行为:

    func textFieldDidBeginEditing(_ textField: UITextField) {
textField.backgroundColor = .red
}

func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) {
textField.backgroundColor = .systemGray
}

关于ios - 编辑时UITextField自定义背景色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61684807/

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