首页 > 解决方案 > UITextField 编辑时自定义背景颜色

问题描述

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

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

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

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

正确的外观

我面临的问题是,一旦我点击 TextField,它就会恢复到默认颜色(我认为它是默认颜色),我无法更改它。

编辑时

所以我所做的是创建一个UIViewRepresentableTextField 的实现,也许这对我的帮助比 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 处于编辑模式时的视图层次结构,并且将自身置于 TextField 前面的选定元素是 UIFieldEditor

UIFieldEditor

标签: iosswiftuitextfieldswiftui

解决方案


首先,不要在 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
    }

推荐阅读