Search code examples
iosswiftuikituibuttonstoryboard

Can we add a button inside Textfield in Storyboard based UIKit application?


I created a textfield and button in storyboard inside a stack view.I want my button to be inside textfield. For this inside code I have written :

    textField.rightView = button
    textField.rightViewMode = .always

In story board I have set height and width constraints for both of them, My button has width 30 and height 30.

enter image description here

I have an error

enter image description here

What constraints should I give to place my button inside Textview.


Solution

    1. AFAIK, dragging a view into UITextField as a left/right view is not permitted on Interface Builder (Storyboard/Xib). Therefore, it must be added programmatically.

    2. You cannot edit the textField rightView frame/constraint directly. To make it work, you need to sub-class UITextField and override the rightViewRect function. Basically, you don't need to provide any constraints for the button. However, the tappable area is only inside the parent view (UITextField).

    class CustomTextField: UITextField {
        override func rightViewRect(forBounds bounds: CGRect) -> CGRect {
            .init(x: self.frame.width - 60, y: 0, width: 60, height: 30)
        }
    }