This time, I would like to implement a cool error message using Swift.
I have specified the color for easy understanding.
Let's set the error view to Pink color and set the lower left and right to 20 and the height to 60.
Outlet connection of textfield, button, view to display error. (textfield、button、errorView) Action connection of button with TouchUp Inside. (buttonTouchUpInside)
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textfield: UITextField!
@IBOutlet weak var button: UIButton!
@IBOutlet weak var errorView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func buttonTouchUpInside(_ sender: Any) {
}
}
The bottom of the view that displays the error is also connected. (errorViewBottom)
This time, I want to display an error when the button is tapped when no characters are entered in the textfield.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textfield: UITextField!
@IBOutlet weak var button: UIButton!
@IBOutlet weak var errorView: UIView!
@IBOutlet weak var errorViewBottom: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
//Hide errorView when the screen is displayed
errorViewBottom.constant = -60
}
//When the button is tapped
@IBAction func buttonTouchUpInside(_ sender: Any) {
//If no characters are entered in the textfield
if textfield.text == "" {
//The main subject is from here
UIView.transition(
//Animated view
with: self.errorView,
//Animation seconds
duration: 0.2,
//Animation specification constant velocity
options: [.curveLinear],
//Processing during animation//Since the X axis does not change, 0, and the Y axis wants to move 20 upwards, so add 20 to the errorView size 60.-Specify 80
animations: {self.errorView.transform = CGAffineTransform(translationX: 0, y: -80)},
//Processing after the animation is finished
completion: { (finished: Bool) in
//Wait 4 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 4.0) {
//Animation again
UIView.transition(
//Animated view
with: self.errorView,
//Animation seconds
duration: 0.2,
//Animation specification constant velocity
options: [.curveLinear],
//Processing during animation//Next time I want to lower it, so specify 80 in the opposite of the previous one
animations: {self.errorView.transform = CGAffineTransform(translationX: 0, y: 80)},
//Processing after the animation is finished//This is the end, so nil
completion: nil
)
}
}
)
}
}
}
This completes! !! !!
Recommended Posts