TextField with Label over the border at Top-Left position

Niraj picture Niraj · Feb 20, 2020 · Viewed 8.4k times · Source

I need to implement outline textfield with placeholder in my swift project one like the Material UI. I tried googling for the same but could not found anything. Anyone know how to achieve it in swift? Reference Images:

enter image description here

uit

Answer

Kishan Bhatiya picture Kishan Bhatiya · Feb 20, 2020

Using this pod, you can get the same design

  1. Take UIView on Storyboard and set constraints
  2. Make class which is a subclass of UIView and import pods MaterialComponents.MaterialTextFields and MaterialComponents.MaterialTextFields_ColorThemer

class CustomOutlinedTxtField: UIView {

private var textFieldControllerFloating: MDCTextInputControllerOutlined!
var textField: MDCTextField!

@IBInspectable var placeHolder: String!
@IBInspectable var value: String!
@IBInspectable var primaryColor: UIColor! = .purple

override open func draw(_ rect: CGRect) {
    super.draw(rect)

    textField.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)

}
open override func awakeFromNib() {
    super.awakeFromNib()
    setUpProperty()
}
func setUpProperty() {
    //Change this properties to change the propperties of text
    textField = MDCTextField(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height))
    textField.placeholder = placeHolder
    textField.text = value

    //Change this properties to change the colors of border around text
    textFieldControllerFloating = MDCTextInputControllerOutlined(textInput: textField)

    textFieldControllerFloating.activeColor = primaryColor
    textFieldControllerFloating.floatingPlaceholderActiveColor = primaryColor
    textFieldControllerFloating.normalColor = UIColor.lightGray
    textFieldControllerFloating.inlinePlaceholderColor = UIColor.lightGray

    //Change this font to make borderRect bigger
    textFieldControllerFloating.inlinePlaceholderFont = UIFont.systemFont(ofSize: 14)
    textFieldControllerFloating.textInsets(UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0))

    self.addSubview(textField)
}

}

  1. Assign that custom class to UIView

enter image description here

Result

enter image description here

enter image description here