是否可以在 SwiftUI 中向 TextField 添加字距调整?

Mul*_*uli 5 swift swiftui

为了匹配样式指南,我必须向文本字段添加字距调整,包括占位符和值本身。

使用 UIKit,我可以这样做:

    class MyTextField: UITextField {
    override func awakeFromNib() {
        super.awakeFromNib()

        // ...

        self.attributedPlaceholder = NSAttributedString(string: self.placeholder ?? "", attributes: [
            //...
            NSAttributedString.Key.kern: 0.3
        ])

        self.attributedText = NSAttributedString(string: "", attributes: [
            // ...
            NSAttributedString.Key.kern: 0.3
        ])
    }
}
Run Code Online (Sandbox Code Playgroud)

在 SwiftUI 中,我发现可以对Text元素应用字距调整效果,如下所示:

    Text("My label with kerning")
       .kerning(0.7)
Run Code Online (Sandbox Code Playgroud)

不幸的是,我找不到一种方法将字距调整样式应用于 TextField 的值或占位符。对这个有什么想法吗?提前致谢

And*_*rew 5

HackingwithSwift有一个简单的教程,展示了如何实现 UITextView。它可以轻松地适应 UITextField。

UIViewRepresentable这是一个向您展示如何使用的快速示例UITextField。设置文本和占位符的字距调整。

struct ContentView: View {

    @State var text = ""

    var body: some View {
        MyTextField(text: $text, placeholder: "Placeholder")
    }

}

struct MyTextField: UIViewRepresentable {
    @Binding var text: String
    var placeholder: String

    func makeUIView(context: Context) -> UITextField {
        return UITextField()
    }

    func updateUIView(_ uiView: UITextField, context: Context) {
        uiView.attributedPlaceholder = NSAttributedString(string: self.placeholder, attributes: [
            NSAttributedString.Key.kern: 0.3
        ])
        uiView.attributedText = NSAttributedString(string: self.text, attributes: [
            NSAttributedString.Key.kern: 0.3
        ])
    }
}
Run Code Online (Sandbox Code Playgroud)

更新

上面的内容不适用于在 attributeText 上设置字距调整。借鉴 Costantino Pistagna 在他的媒体文章中所做的出色工作,我们需要做更多的工作。

首先,我们需要创建一个UITextField允许我们访问委托方法的包装版本。

class WrappableTextField: UITextField, UITextFieldDelegate {
    var textFieldChangedHandler: ((String)->Void)?
    var onCommitHandler: (()->Void)?

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if let nextField = textField.superview?.superview?.viewWithTag(textField.tag + 1) as? UITextField {
            nextField.becomeFirstResponder()
        } else {
            textField.resignFirstResponder()
        }
        return false
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if let currentValue = textField.text as NSString? {
            let proposedValue = currentValue.replacingCharacters(in: range, with: string)
            print(proposedValue)
            self.attributedText = NSAttributedString(string: currentValue as String, attributes: [
                NSAttributedString.Key.kern: 10
            ])
            textFieldChangedHandler?(proposedValue as String)
        }
        return true
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        onCommitHandler?()
    }
}
Run Code Online (Sandbox Code Playgroud)

由于shouldChangeCharactersIn每次文本更改时都会调用委托方法,因此我们应该使用它来更新值attributedText。我尝试首先使用proposedVale但它会使字符加倍,如果我们使用它它会按预期工作currentValue

现在我们可以WrappedTextFieldUIViewRepresentable.

struct SATextField: UIViewRepresentable {
    private let tmpView = WrappableTextField()

    //var exposed to SwiftUI object init
    var tag:Int = 0
    var placeholder:String?
    var changeHandler:((String)->Void)?
    var onCommitHandler:(()->Void)?

    func makeUIView(context: UIViewRepresentableContext<SATextField>) -> WrappableTextField {
        tmpView.tag = tag
        tmpView.delegate = tmpView
        tmpView.placeholder = placeholder
        tmpView.attributedPlaceholder = NSAttributedString(string: self.placeholder ?? "", attributes: [
            NSAttributedString.Key.kern: 10
        ])
        tmpView.onCommitHandler = onCommitHandler
        tmpView.textFieldChangedHandler = changeHandler
        return tmpView
    }

    func updateUIView(_ uiView: WrappableTextField, context: UIViewRepresentableContext<SATextField>) {
        uiView.setContentHuggingPriority(.defaultHigh, for: .vertical)
        uiView.setContentHuggingPriority(.defaultLow, for: .horizontal)
    }
}
Run Code Online (Sandbox Code Playgroud)

我们在 中设置占位符的属性文本makeUIView。占位符文本不会更新,因此我们无需担心更改它。

下面是我们如何使用它:

struct ContentView: View {

    @State var text = ""

    var body: some View {
        SATextField(tag: 0, placeholder: "Placeholder", changeHandler: { (newText) in
            self.text = newText
        }) {
            // do something when the editing of this textfield ends
        }
    }
}
Run Code Online (Sandbox Code Playgroud)