Reputation: 97
I want to create an animation for my UItextfield. To do this, I created a sub class of UITextField and I stored my code there:
import Foundation
import UIKit
class textfieldEdit: UITextField, UITextFieldDelegate {
let border = CALayer()
let width = CGFloat(2.0)
required init?(coder aDecoder: (NSCoder!)) {
super.init(coder: aDecoder)
self.delegate=self;
border.borderColor = UIColor( red: 216/255, green: 216/255, blue: 216/255, alpha: 100 ).cgColor
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: self.frame.size.height)
border.borderWidth = width
self.layer.addSublayer(border)
self.layer.masksToBounds = true
}
override func draw(_ rect: CGRect) {
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: self.frame.size.height)
}
override func awakeFromNib() {
super.awakeFromNib()
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: self.frame.size.height)
}
}
However, when someone clicks inside the textfield, I want to update the border of the textfield and make it green. Is there an efficient way to do this? I tried to assign a function to whenever someone touches inside of the textbox in my main view controller but it doesnt seem to work.
Upvotes: 4
Views: 3047
Reputation: 13459
I'd suggest not combining these behaviours. Instead, add an UIView with "Touches Enabled", then add a touch listener to this view, on tap send a message to a convenience method in your custom uitextfield, or just change the looks of it directly.
This also works with an UIButton.
For layout purposes just make the button or view have the same edge constraints as your label as well as its center X and Y position.
Don't forget to call the "setNeedsDisplay" for your custom text label to force it to redraw.
What is the most robust way to force a UIView to redraw?
Edit: If you are only interested in changing the border color when the UITextfield is currently being edited, add a delegate to it and change the appearance accordingly once when it becomes first responder (is being edited) and once when it resigns being first responder (stops being edited):
How to know when UITextView became first responder
Change border here:
optional func textViewDidBeginEditing(_ textView: UITextView)
https://developer.apple.com/documentation/uikit/uitextviewdelegate/1618610-textviewdidbeginediting
And set it back to normal here:
optional func textViewDidEndEditing(_ textView: UITextView)
https://developer.apple.com/documentation/uikit/uitextviewdelegate/1618628-textviewdidendediting
Upvotes: 2