I want to create a custom text field when I started to input label should float to top-left. I know there is some libraries to make that but I want to do it myself. I found some blog about that but these are generally make that in viewController but I'll use this format in many pages so I think I should create a custom text field and use this where I need. I tried to use codes in my custom text field but nothings happen.
There is codes which working in viewController :
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var textLabel: UILabel!
@IBOutlet weak var textLabelTop: NSLayoutConstraint!
@IBOutlet weak var textLabelLeading: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
textField.delegate = self
// Create a padding view for padding on left
let indentView = UIView(frame: CGRect(x: 0, y: 10, width: 10, height: 20))
textField.leftView = indentView
textField.leftViewMode = .always
// Create a padding view for padding on right
textField.rightView = UIView(frame: CGRect(x: 0, y: 10, width: 15, height: textField.frame.height))
}
func textFieldDidBeginEditing(_ textField: UITextField) {
floatTitle()
performAnimation(transform: CGAffineTransform(scaleX: 1, y: 1))
}
// This is where we adjust constraint and the label will float to the top
func floatTitle() {
textLabel.font = textLabel.font?.withSize(8)
textLabelTop.constant = 7
textLabelLeading.constant = 7
}
// By adding a little animation
private func performAnimation(transform: CGAffineTransform) {
UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseOut, animations: {
self.textLabel.transform = transform
self.view.layoutIfNeeded()
}, completion: nil)
}
}
How can I implement this codes to custom text field ?
I found that medium blog and use that for my project.
https://medium.com/sprinthub/creating-a-custom-floating-label-style-text-field-in-swift-f9f6aeaf39fe