1

I have a UITextView and need to add a CLEAR button below it such that when it is pressed it will clear that UITextView.

Not understanding how to connect the two elements or create a delegate in ObjC. Can do it in VisualBasic.

Thank you.

2

1 Answer 1

0

You can use 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)
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.