8.7 C
Canberra
Saturday, July 26, 2025

ios – SwiftUI – Strikethrough on TextField


SwiftUI TextFields 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 contents 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 contents, by simply writing the modifier as soon as. Beneath the hood, it is truly simply setting a (private) EnvironmentValues, i.e. .surroundings(.someInternalThing, ...).

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

[td_block_social_counter facebook="tagdiv" twitter="tagdivofficial" youtube="tagdiv" style="style8 td-social-boxed td-social-font-icons" tdc_css="eyJhbGwiOnsibWFyZ2luLWJvdHRvbSI6IjM4IiwiZGlzcGxheSI6IiJ9LCJwb3J0cmFpdCI6eyJtYXJnaW4tYm90dG9tIjoiMzAiLCJkaXNwbGF5IjoiIn0sInBvcnRyYWl0X21heF93aWR0aCI6MTAxOCwicG9ydHJhaXRfbWluX3dpZHRoIjo3Njh9" custom_title="Stay Connected" block_template_id="td_block_template_8" f_header_font_family="712" f_header_font_transform="uppercase" f_header_font_weight="500" f_header_font_size="17" border_color="#dd3333"]
- Advertisement -spot_img

Latest Articles