Question

I want to show clear button in UITextView while editing. i know how to add in text field but don't know how to add clear button in text view.

Was it helpful?

Solution

UITextView doesn't come with a stock clear button, like UITextField does.

If you want a button to clear the text view, just add a custom button to the view and link it to a proper clear action in the controller code.

Otherwise, if you just need a one-line editable text input view, just go ahead and use a UITextField.

OTHER TIPS

Custom textView with clear button:

final class ClearableTextView: UITextView {
    
    private lazy var clearButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(systemName: "clear.fill"), for: .normal)
        button.setTitle(nil, for: .normal)
        button.tintColor = .gray
        addSubview(button)
        return button
    } ()
    let clearButtonSize: CGFloat = 30
    let clearButtonRightInset: CGFloat = 4
    
    
    override var bounds: CGRect {
        didSet {
            clearButton.frame = CGRect(
                x: bounds.maxX - clearButtonSize - clearButtonRightInset,
                y: bounds.midY - clearButtonSize / 2,
                width: clearButtonSize,
                height: clearButtonSize
            )
        }
    }
    
    public override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setup()
    }
    
    public required init?(coder: NSCoder) {
        super .init(coder: coder)
        setup()
    }
    
    private func setup() {
        clearButton.addTarget(self, action: #selector(onClearClick), for: .touchUpInside)
        textContainerInset.right = clearButtonSize + clearButtonRightInset
    }
    
    @objc private func onClearClick() {
        text = nil
        delegate?.textViewDidChange?(self)
    }
}

If you are using Storyboards, go to the Attributes Inspector and check

Clear when editing begins

If you want to do it by code:

theTextField.clearButtonMode = UITextFieldViewModeWhileEditing
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top