I'm trying to animate a textfield with a custom class, when I change my left constraint from 0 to (self.bounds.width - self.bounds.width/3) the animation is not smooth, but when I set it back to 0 it works perfectly.
Here is part of my custom class:
lazy var leftConstraint = NSLayoutConstraint(item: placeholderLabel, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 0)
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.delegate = self
self.addSubview(placeholderLabel)
self.bringSubview(toFront: self)
addConstraints()
}
func addConstraints() {
placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: placeholderLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: self.bounds.height).isActive = true
self.leftConstraint.isActive = true
NSLayoutConstraint(item: placeholderLabel, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: placeholderLabel, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0).isActive = true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
animate(constant: self.bounds.width - self.bounds.width/3)
self.bringSubview(toFront: placeholderLabel)
}
func textFieldDidEndEditing(_ textField: UITextField) {
if (textField.text?.isEmpty)!{
animate(constant: 0)
self.bringSubview(toFront: self)
}
}
func animate(constant: CGFloat) {
self.leftConstraint.constant = constant
UIView.animate(withDuration: 0.15) {
self.layoutIfNeeded()
}
}