SwiftUI TextField
s don’t assist strikethroughs. You may wrap a UITextField
and set its defaultTextAttributes
as an alternative.
struct StrikethroughUITextField: UIViewRepresentable {
@Binding var textual content: String
init(textual content: Binding) {
self._text = textual content
}
func makeUIView(context: Context) -> UITextField {
let textField = UITextField(body: .zero)
textField.defaultTextAttributes = [
.strikethroughStyle: NSUnderlineStyle.single.rawValue,
.strikethroughColor: UIColor.black
]
textField.addTarget(context.coordinator, motion: #selector(Coordinator.textDidChange), for: .editingChanged)
return textField
}
func updateUIView(_ uiView: UITextField, context: Context) {
context.coordinator.textCallback = { textual content = $0 }
uiView.textual content = textual content
}
func makeCoordinator() -> Coordinator {
.init()
}
@MainActor
class Coordinator: NSObject {
var textCallback: ((String) -> Void)?
@objc
func textDidChange(_ textField: UITextField) {
textCallback?(textField.textual content ?? "")
}
}
}
So far as I do know, solely Textual content
s will probably be affected by strikethrough()
, however you possibly can nonetheless apply it to any View
. That is by design – this design permits you to apply strikethrough to many Textual content
s, by simply writing the modifier as soon as. Beneath the hood, it is truly simply setting a (private) EnvironmentValues
, i.e. .surroundings(.someInternalThing, ...)
.