Why is layoutIfNeeded() not animating navigationBar's BarButtonItem? - ios

I am trying to make a simple e-commerce app with a dynamic barButton to show users their total cart cost. I wanted to add an animation to it. So that the button needs to collapse and expand whenever its value changes. I used layoutIfNeeded() method after updating button's constraints. However the animation is not working. The code is a bit complex so I am sharing a code sample and a video to give you a rough idea what I have done so far. What could be changed to get desired animation?
Gif
Code
class ProductsViewController: UIViewController {
...
var cartBarButton: UIBarButtonItem!
var cartBarButtonWidthConstraint: NSLayoutConstraint?
var price: Double = 0
...
override func viewDidLoad() {
super.viewDidLoad()
configureCartButton()
...
}
func configureCartButton() {
let cartButton = CustomCartButton(color: color, image: image, title: price.currencyString)
cartButton.addTarget(self, action: #selector(updateCartCost), for: .touchUpInside)
cartBarButton = UIBarButtonItem(customView: cartButton)
cartBarButton.customView?.translatesAutoresizingMaskIntoConstraints = false
cartBarButtonWidthConstraint = cartBarButton.expand(considering: price) // expand() method is extension to UIBarButtonItem, returns barButton's widthAnchor constraint
cartBarButtonWidthConstraint?.isActive = true
navigationItem.rightBarButtonItem = cartBarButton
}
#objc private func updateCartCost() {
cartBarButtonWidthConstraint?.isActive = false
cartBarButtonWidthConstraint = cartBarButton.collapse(to: 25) // collapse() method is an extension to UIBarButtonItem
cartBarButtonWidthConstraint?.isActive = true
UIView.animate(withDuration: 1) {
self.view.layoutIfNeeded()
}
price += 90
cartBarButtonWidthConstraint?.isActive = false
cartBarButtonWidthConstraint = cartBarButton.expand(considering: price)
cartBarButtonWidthConstraint?.isActive = true
UIView.animate(withDuration: 1) {
self.view.layoutIfNeeded()
}
self.cartButton.title = self.price.currencyString
}
}

You are changing the constraint to collapse and the constraint to expand at the same time and doing both animations at the same time.
You should move all of the code to do the expansion in the completion handler of the collapse animation. This should allow the two changes to happen one after the other instead being all done at once.
Something like this (not verified it will compile but it gives you the idea):
#objc private func updateCartCost() {
cartBarButtonWidthConstraint?.isActive = false
cartBarButtonWidthConstraint = cartBarButton.collapse(to: 25) // collapse() method is an extension to UIBarButtonItem
cartBarButtonWidthConstraint?.isActive = true
UIView.animate(withDuration: 1, animations: {
self.view.layoutIfNeeded()
}) { finished in
price += 90
cartBarButtonWidthConstraint?.isActive = false
cartBarButtonWidthConstraint = cartBarButton.expand(considering: price)
cartBarButtonWidthConstraint?.isActive = true
UIView.animate(withDuration: 1) {
self.view.layoutIfNeeded()
}
}
self.cartButton.title = self.price.currencyString
}

Related

Interacting with a ViewController that has Multiple child ViewControllers

I have a parent viewController and a child viewController. The childViewController is like a card and functions similar to Apple's stock or map app. I can expand or collapse it and interact with the buttons within it. The only problem is that I can't interact with any buttons within the parent viewController. Anyone know what's the problem.
class BaseViewController: UIViewController {
enum CardState {
case expanded
case collapsed
}
var cardViewController: CardViewController!
var visualEffectView: UIVisualEffectView!
lazy var deviceCardHeight: CGFloat = view.frame.height - (view.frame.height / 6)
lazy var cardHeight: CGFloat = deviceCardHeight
let cardHandleAreaHeight: CGFloat = 65
var cardVisible = false
var nextState: CardState {
return cardVisible ? .collapsed : .expanded
}
override func viewDidLoad() {
super.viewDidLoad()
setupCard()
}
#IBAction func expandCard(_ sender: Any) {
print("Button Pressed")
}
func setupCard() {
cardViewController = CardViewController(nibName: "CardViewController", bundle: nil)
self.addChild(cardViewController)
self.view.addSubview(cardViewController.view)
//Set up frame of cardView
cardViewController.view.frame = CGRect(x: 0, y: view.frame.height - cardHandleAreaHeight, width: view.frame.width, height: cardHeight)
cardViewController.view.clipsToBounds = true
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleCardTap(recognizer:)))
cardViewController.handleArea.addGestureRecognizer(tapGestureRecognizer)
}
#objc func handleCardTap(recognizer: UITapGestureRecognizer) {
switch recognizer.state {
case .ended:
animationTransitionIfNeeded(state: nextState, duration: 0.9)
default:
break
}
}
func animationTransitionIfNeeded(state: CardState, duration: TimeInterval) {
if runningAnimations.isEmpty {
let frameAnimator = UIViewPropertyAnimator(duration: duration, dampingRatio: 1) {
switch state {
case .expanded:
self.cardViewController.view.frame.origin.y = self.view.frame.height - self.cardHeight
case .collapsed:
self.cardViewController.view.frame.origin.y = self.view.frame.height - self.cardHandleAreaHeight
}
}
frameAnimator.addCompletion { _ in
//if true set to false, if false set to true
self.cardVisible = !self.cardVisible
self.runningAnimations.removeAll()
}
frameAnimator.startAnimation()
runningAnimations.append(frameAnimator)
let cornerRadiusAnimator = UIViewPropertyAnimator(duration: duration, curve: .linear) {
switch state {
case .expanded:
self.cardViewController.view.layer.cornerRadius = 12
case .collapsed:
self.cardViewController.view.layer.cornerRadius = 0
}
}
cornerRadiusAnimator.startAnimation()
}
}
'Can't interact' should mean that you can't press. If that is the case the most likely cause is that the button is covered with something (it could be transparent so ensure when testing that there is no transparent backgrounds until you resolve this). The other possible reason would be that you have set some property of the button that would cause this behavior, but you would probably know that so it is almost certainly the former.
I solve it. This code should work perfectly. The reason why it didn't before was because I added in a visualEffectView. It was covering the parent.

invert place of the UIView, with animation

I'm looking for the best way to invert the place of two UIView, with animation if possible (first i need to change the place, animation is optionnal).
viewController :
So, i want view1 to invert his place with the view2. The views are set with autolayout in the storyboard at the init.
if state == true {
view1 at the top
view2 at the bot
} else {
view 2 at the top
view 1 at the top
}
I've tried to take view.frame.(x, y, width, height) from the other view and set it to the view but it doesn't work.
I think the best way to do this would be to have a topConstraint for both views connected to the header and then change their values and animate the transition. You can do it in a way similar to this:
class MyViewController: UIViewController {
var view1TopConstraint: NSLayoutConstraint!
var view2TopConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
view1TopConstraint = view1.topAnchor.constraintEqualToAnchor(header.bottomAnchor, constant: 0)
view1TopConstraint.isActive = true
view2TopConstraint = view2.topAnchor.constraintEqualToAnchor(header.bottomAnchor, constant: view1.frame.height)
view2TopConstraint.isActive = true
}
func changeView2ToTop() {
UIView.animateWithDuration(0.2, animations: { //this will animate the change between 2 and 1 where 2 is at the top now
self.view2TopConstraint.constant = 0
self.view1TopConstraint.constant = view2.frame.height
//or knowing that view2.frame.height represents 30% of the total view frame you can do like this as well
// self.view1TopConstraint.constant = view.frame.height * 0.3
self.view.layoutIfNeeded()
})
}
You could also create the NSLayoutConstraint in storyboard and have an outlet instead of the variable I have created or set the top constraint for both views in storyboard at "remove at build time" if you are doing both. This way you won't have 2 top constraints and no constraint warrning
I Made an Example: https://dl.dropboxusercontent.com/u/24078452/MovingView.zip
I just created a Storyboard with 3 View, Header, View 1 (Red) and View 2 (Yellow). Then I added IBoutlets and animated them at viewDid Appear, here is the code:
import UIKit
class ViewController: UIViewController {
var position1: CGRect?
var position2: CGRect?
#IBOutlet weak var view1: UIView!
#IBOutlet weak var view2: UIView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
position1 = view1.frame
position2 = view2.frame
UIView.animate(withDuration: 2.5) {
self.view1.frame = self.position2!
self.view2.frame = self.position1!
}
}
}
Hello #Makaille I have try to resolve your problem.
I have made an example, which will help you for your required implementation.
Check here: Source Code
I hope, it will going to help you.
#IBAction func toggle(_ sender: UIButton) {
sender.isUserInteractionEnabled = false
if(sender.isSelected){
let topPinConstantValue = layout_view2TopPin.constant
layout_view1TopPin.constant = topPinConstantValue
layout_view2TopPin.priority = 249
layout_view1BottomPin_to_View2Top.priority = 999
layout_view1TopPin.priority = 999
layout_view2BottomPin_ToView1Top.priority = 249
UIView.animate(withDuration: 0.3, animations: {
self.view.layoutIfNeeded()
}, completion: { (value) in
if(value){
sender.isUserInteractionEnabled = true
}
})
} else {
let topPinConstantValue = layout_view1TopPin.constant
layout_view2TopPin.constant = topPinConstantValue
layout_view1TopPin.priority = 249
layout_view2BottomPin_ToView1Top.priority = 999
layout_view2TopPin.priority = 999
layout_view1BottomPin_to_View2Top.priority = 249
UIView.animate(withDuration: 0.3, animations: {
self.view.layoutIfNeeded()
}, completion: { (value) in
if(value){
sender.isUserInteractionEnabled = true
}
})
}
sender.isSelected = !sender.isSelected
}

Hide navigation bar without moving scrollView

I have a viewController where am showing image for adding the zooming functionality I added the scrollView in viewController and inside of ScrollView I added ImageView everything is working fine expect of one thing, am hiding, and showing the bars (navigation bar + tab bar) on tap but when hiding them my imageView moves upside see the below images
See here's the image and the bars.
Here I just tapped on the view and bars got hidden but as you can see my imageView is also moved from its previous place, this is what I want to solve I don't want to move my imageView.
This is how am hiding my navigation bar:
func tabBarIsVisible() ->Bool {
return self.tabBarController?.tabBar.frame.origin.y < CGRectGetMaxY(self.view.frame)
}
func toggle(sender: AnyObject) {
navigationController?.setNavigationBarHidden(navigationController?.navigationBarHidden == false, animated: true)
setTabBarVisible(!tabBarIsVisible(), animated: true)
}
any idea how can I hide and show the bars without affecting my other Views?
The problem is that you need to set the constraint of your imageView to your superView, not TopLayoutGuide or BottomLayoutGuide.
like so:
Then you can do something like this to make the it smootly with animation:
import UIKit
class ViewController: UIViewController {
#IBOutlet var imageView: UIImageView!
var barIsHidden = false
var navigationBarHeight: CGFloat = 0
var tabBarHeight: CGFloat = 0
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.hideAndShowBar))
view.addGestureRecognizer(tapGesture)
navigationBarHeight = (self.navigationController?.navigationBar.frame.size.height)!
tabBarHeight = (self.tabBarController?.tabBar.frame.size.height)!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func hideAndShowBar() {
print("tap!!")
if barIsHidden == false {
UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveEaseOut, animations: {
// fade animation
self.navigationController?.navigationBar.alpha = 0.0
self.tabBarController?.tabBar.alpha = 0.0
// set height animation
self.navigationController?.navigationBar.frame.size.height = 0.0
self.tabBarController?.tabBar.frame.size.height = 0.0
}, completion: { (_) in
self.barIsHidden = true
})
} else {
UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveEaseOut, animations: {
// fade animation
self.navigationController?.navigationBar.alpha = 1.0
self.tabBarController?.tabBar.alpha = 1.0
// set height animation
self.navigationController?.navigationBar.frame.size.height = self.navigationBarHeight
self.tabBarController?.tabBar.frame.size.height = self.tabBarHeight
}, completion: { (_) in
self.barIsHidden = false
})
}
}
}
Here is the result:
I have created an example project for you at: https://github.com/khuong291/Swift_Example_Series
You can see it at project 37
Hope this will help you.

Implementing UIDatePicker and UIPickerView with a UIButton

I'm implementing a user form in an iOS app that uses both a UIPickerView and UIDatePicker as input devices from a user. I've implemented each of these as a view external to the main UIViewController in the scene and have them showing and hiding using autolayout by adding and removing constraints.
Here's my problem: I'm maintaining separate constraints and hide/show methods for animating each of these views in and out. It's a lot of repeat code and I get the sense that there has to be a cleaner way to do this, since it seems to be a very common design pattern in iOS apps. I'm fairly new at this, so I feel like I'm missing something.
Is there a better design pattern than this for using multiple input devices to UIButtons??
Here's a sampling of the code i'm using to maintain this...
var datePickerViewBottomConstraint: NSLayoutConstraint!
var datePickerViewTopConstraint: NSLayoutConstraint!
var storagePickerViewBottomConstraint: NSLayoutConstraint!
var storagePickerViewTopConstraint: NSLayoutConstraint!
#IBAction func storageButtonClicked(sender: UITextField) {
storagePickerView.translatesAutoresizingMaskIntoConstraints = false
storagePickerViewBottomConstraint = storagePickerView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor)
UIView.animateWithDuration(0.4, animations: {
self.storagePickerViewTopConstraint.active = false
self.storagePickerViewBottomConstraint.active = true
self.view.layoutIfNeeded()
})
}
#IBAction func datePumpedClicked(sender: UIButton) {
datePickerView.translatesAutoresizingMaskIntoConstraints = false
datePickerViewBottomConstraint = datePickerView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor)
UIView.animateWithDuration(0.4, animations: {
self.datePickerViewTopConstraint.active = false
self.datePickerViewBottomConstraint.active = true
self.view.layoutIfNeeded()
})
}
#IBAction func datePickerDismiss(sender: AnyObject) {
datePumpedLabel.setTitle(Global.dateFormatter.stringFromDate(datePicker.date), forState: UIControlState.Normal)
datePickerView.translatesAutoresizingMaskIntoConstraints = false
datePickerViewTopConstraint = datePickerView.topAnchor.constraintEqualToAnchor(view.bottomAnchor)
UIView.animateWithDuration(0.4, animations: {
self.datePickerViewBottomConstraint.active = false
self.datePickerViewTopConstraint.active = true
self.view.layoutIfNeeded()
})
}
#IBAction func storagePickerDismiss(sender: AnyObject) {
storagePickerView.translatesAutoresizingMaskIntoConstraints = false
storagePickerViewTopConstraint = storagePickerView.topAnchor.constraintEqualToAnchor(view.bottomAnchor)
UIView.animateWithDuration(0.4, animations: {
self.storagePickerViewBottomConstraint.active = false
self.storagePickerViewTopConstraint.active = true
self.view.layoutIfNeeded()
})
}
Here's a screenshot of my storyboard...
Storyboard
You guys, I figured out a better way!
The thing that I was missing originally is that when you remove views from the superview, all the constraints are deleted. This makes things a lot easier.
I kept 1 constraint class variable for the view that is currently being shown, so the view can animate down out of place.
I also added a "setup" function to get the view in place on viewdidload(). Without this the view will always animate in from the top the first time it appears (couldn't figure out a way around this).
Here's what I used:
var secondaryMenuBottomConstraint: NSLayoutConstraint!
func setupSecondaryMenu(secondaryMenu: UIView){
secondaryMenu.translatesAutoresizingMaskIntoConstraints = false
let topConstraint = secondaryMenu.topAnchor.constraintEqualToAnchor(view.bottomAnchor)
let leftConstraint = secondaryMenu.leftAnchor.constraintEqualToAnchor(view.leftAnchor)
let rightConstraint = secondaryMenu.rightAnchor.constraintEqualToAnchor(view.rightAnchor)
view.addSubview(secondaryMenu)
NSLayoutConstraint.activateConstraints([topConstraint, leftConstraint, rightConstraint])
self.view.layoutIfNeeded()
secondaryMenu.removeFromSuperview()
}
func showSecondaryMenu(secondaryMenu: UIView){
//Close any open keyboards
amountTextField.resignFirstResponder()
notesTextField.resignFirstResponder()
//Add the view and then add constraints to show the submenu below the current view
secondaryMenu.translatesAutoresizingMaskIntoConstraints = false
let topConstraint = secondaryMenu.topAnchor.constraintEqualToAnchor(view.bottomAnchor)
let leftConstraint = secondaryMenu.leftAnchor.constraintEqualToAnchor(view.leftAnchor)
let rightConstraint = secondaryMenu.rightAnchor.constraintEqualToAnchor(view.rightAnchor)
view.addSubview(secondaryMenu)
NSLayoutConstraint.activateConstraints([topConstraint, leftConstraint, rightConstraint])
secondaryMenuBottomConstraint = secondaryMenu.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor)
//animate the view up into place
UIView.animateWithDuration(0.4, animations: {
topConstraint.active = false
self.secondaryMenuBottomConstraint.active = true
self.view.layoutIfNeeded()
})
}
func dismissSecondaryMenu(secondaryMenu: UIView){
if secondaryMenu.superview != nil {
secondaryMenu.translatesAutoresizingMaskIntoConstraints = false
let secondaryMenuTopConstraint = secondaryMenu.topAnchor.constraintEqualToAnchor(view.bottomAnchor)
self.secondaryMenuBottomConstraint.active = false
UIView.animateWithDuration(0.4, animations: {
secondaryMenuTopConstraint.active = true
self.view.layoutIfNeeded()
}, completion: {(finished:Bool) in
secondaryMenu.removeFromSuperview()
})
}
}

PlaceHolder animates when start typing in TextField in iOS

How to set this type of animation in UITextField? Nowadays, Many apps are using this.
I've found the solution. You can manage this type of animation using multiple labels, and show-hide those labels into textFieldDidBeginEditing method.
If you want nice animation same as you describe into your question, then try once following third party repository for UITextField.
JVFloatLabeledTextField
UIFloatLabelTextField
FloatLabelFields
If you are looking for the UITextView equivalent of this animation, please visit UIFloatLabelTextView repository.
This problem can be solved logically with the use of multiple labels and text-fields and later we can add animation if needed. I will like to explain this problem using three images, namely Img1, Img2 and Img3.
Img1 points to storyboard, where we have designed our interface. Here we have used three Labels each followed by TextField and UIView(line below Textfield).
Img2: It points to the initial screen when the app launches or when we press the "Sign up" Button at the bottom, which resets the screen. In this Image, the labels are hidden as textfields are blank with and view color is gray.
Img3: This image reflects the editing of Textfield. As we start editing text field(here the first one, namely name), the label shows up, size of textfield decreases, placeholder changes and color of view changes to black.
We need to keep one more thing in mind, when we stop editing any textfield and if it is still blank then set it properties to original.
I am adding code for this Question which I was asked as assignment in an interview.
import UIKit
class FloatingLabelViewController: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate {
//UITextFieldDelegate - protocol defines methods that you use to manage the editing and validation of text in a UITextField object. All of the methods of this protocol are optional.
//UINavigationControllerDelegate - Use a navigation controller delegate (a custom object that implements this protocol) to modify behavior when a view controller is pushed or popped from the navigation stack of a UINavigationController object.
#IBOutlet weak var NameLbl: UILabel!
#IBOutlet weak var EmailLbl: UILabel!
#IBOutlet weak var PasswordLbl: UILabel!
#IBOutlet weak var NameTxf: UITextField!
#IBOutlet weak var EmailTxf: UITextField!
#IBOutlet weak var PasswordTxf: UITextField!
#IBOutlet weak var SignUpBtn: UIButton!
#IBOutlet weak var NameView: UIView!
#IBOutlet weak var EmailView: UIView!
#IBOutlet weak var PasswordView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
NameTxf.delegate = self
EmailTxf.delegate = self
PasswordTxf.delegate = self
self.property()
//black is varaiable here
//setTitleColor - Sets the color of the title to use for the specified state
//var layer - The view’s Core Animation layer used for rendering. this propert is never nil
//cg color - Quartz color refernce
SignUpBtn.backgroundColor = UIColor.black
SignUpBtn.setTitleColor(UIColor.white, for: .normal)
SignUpBtn.layer.borderWidth = 1
SignUpBtn.layer.borderColor = UIColor.black.cgColor
//Tap guesture recognizer to hide keyboard
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(FloatingLabelViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
// UITapGestureRecognizer - UITapGestureRecognizer is a concrete subclass of UIGestureRecognizer that looks for single or multiple taps. For the gesture to be recognized, the specified number of fingers must tap the view a specified number of times.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//textFieldShouldReturn - Asks the delegate if the text field should process the pressing of the return button. The text field calls this method whenever the user taps the return button. YES if the text field should implement its default behavior for the return button; otherwise, NO.
// endEditing - Causes the view (or one of its embedded text fields) to resign the first responder status.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
//When user Starts Editing the textfield
// textFieldDidBeginEditing - Tells the delegate that editing began in the specified text field
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == self.NameTxf
{
self.NameTxf.font = UIFont.italicSystemFont(ofSize: 15)
self.NameLbl.isHidden = false
self.NameLbl.text = self.NameTxf.placeholder
self.NameTxf.placeholder = "First Last"
NameView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
}
else if textField == self.EmailTxf
{
self.EmailTxf.font = UIFont.italicSystemFont(ofSize: 15)
self.EmailLbl.isHidden = false
self.EmailLbl.text = self.EmailTxf.placeholder
self.EmailTxf.placeholder = "abc#gmail.com"
EmailView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
}
else if textField == self.PasswordTxf
{
self.PasswordTxf.font = UIFont.italicSystemFont(ofSize: 15)
self.PasswordLbl.isHidden = false
self.PasswordLbl.text = self.PasswordTxf.placeholder
self.PasswordTxf.placeholder = "........."
PasswordView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
}
}
//When User End editing the textfield.
// textFieldDidEndEditing - Tells the delegate that editing stopped for the specified text field.
func textFieldDidEndEditing(_ textField: UITextField) {
//Checkes if textfield is empty or not after after user ends editing.
if textField == self.NameTxf
{
if self.NameTxf.text == ""
{
self.NameTxf.font = UIFont.italicSystemFont(ofSize: 25)
self.NameLbl.isHidden = true
self.NameTxf.placeholder = "Name"
NameView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
}
}
else if textField == self.EmailTxf
{
if self.EmailTxf.text == ""
{
self.EmailTxf.font = UIFont.italicSystemFont(ofSize: 25)
self.EmailLbl.isHidden = true
self.EmailTxf.placeholder = "Email"
EmailView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
}
}
else if textField == self.PasswordTxf
{
if self.PasswordTxf.text == ""
{
self.PasswordTxf.font = UIFont.italicSystemFont(ofSize: 25)
self.PasswordLbl.isHidden = true
self.PasswordTxf.placeholder = "Password"
PasswordView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
}
}
}
//Action on SingUp button Clicked.
#IBAction func signupClicked(_ sender: Any) {
self.property()
self.dismissKeyboard() //TO dismiss the Keyboard on the click of SIGNUP button.
}
//Function to set the property of Textfields, Views corresponding to TextFields and Labels.
func property(){
NameLbl.isHidden = true
EmailLbl.isHidden = true
PasswordLbl.isHidden = true
NameTxf.text = ""
EmailTxf.text = ""
PasswordTxf.text = ""
NameTxf.placeholder = "Name"
EmailTxf.placeholder = "Email"
PasswordTxf.placeholder = "Password"
self.NameTxf.font = UIFont.italicSystemFont(ofSize: 25)
self.EmailTxf.font = UIFont.italicSystemFont(ofSize: 25)
self.PasswordTxf.font = UIFont.italicSystemFont(ofSize: 25)
EmailTxf.keyboardType = UIKeyboardType.emailAddress
PasswordTxf.isSecureTextEntry = true
NameTxf.autocorrectionType = .no
EmailTxf.autocorrectionType = .no
NameView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
EmailView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
PasswordView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
}
}
For Swift 4.0 and 4.2
Check this library for floating textField
https://github.com/hasnine/iOSUtilitiesSource
Code:
enum placeholderDirection: String {
case placeholderUp = "up"
case placeholderDown = "down"
}
public class IuFloatingTextFiledPlaceHolder: UITextField {
var enableMaterialPlaceHolder : Bool = true
var placeholderAttributes = NSDictionary()
var lblPlaceHolder = UILabel()
var defaultFont = UIFont()
var difference: CGFloat = 22.0
var directionMaterial = placeholderDirection.placeholderUp
var isUnderLineAvailabe : Bool = true
override init(frame: CGRect) {
super.init(frame: frame)
Initialize ()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
Initialize ()
}
func Initialize(){
self.clipsToBounds = false
self.addTarget(self, action: #selector(IuFloatingTextFiledPlaceHolder.textFieldDidChange), for: .editingChanged)
self.EnableMaterialPlaceHolder(enableMaterialPlaceHolder: true)
if isUnderLineAvailabe {
let underLine = UIImageView()
underLine.backgroundColor = UIColor.init(red: 197/255.0, green: 197/255.0, blue: 197/255.0, alpha: 0.8)
// underLine.frame = CGRectMake(0, self.frame.size.height-1, self.frame.size.width, 1)
underLine.frame = CGRect(x: 0, y: self.frame.size.height-1, width : self.frame.size.width, height : 1)
underLine.clipsToBounds = true
self.addSubview(underLine)
}
defaultFont = self.font!
}
#IBInspectable var placeHolderColor: UIColor? = UIColor.lightGray {
didSet {
self.attributedPlaceholder = NSAttributedString(string: self.placeholder! as String ,
attributes:[NSAttributedString.Key.foregroundColor: placeHolderColor!])
}
}
override public var placeholder:String? {
didSet {
// NSLog("placeholder = \(placeholder)")
}
willSet {
let atts = [NSAttributedString.Key.foregroundColor.rawValue: UIColor.lightGray, NSAttributedString.Key.font: UIFont.labelFontSize] as! [NSAttributedString.Key : Any]
self.attributedPlaceholder = NSAttributedString(string: newValue!, attributes:atts)
self.EnableMaterialPlaceHolder(enableMaterialPlaceHolder: self.enableMaterialPlaceHolder)
}
}
override public var attributedText:NSAttributedString? {
didSet {
// NSLog("text = \(text)")
}
willSet {
if (self.placeholder != nil) && (self.text != "")
{
let string = NSString(string : self.placeholder!)
self.placeholderText(string)
}
}
}
#objc func textFieldDidChange(){
if self.enableMaterialPlaceHolder {
if (self.text == nil) || (self.text?.count)! > 0 {
self.lblPlaceHolder.alpha = 1
self.attributedPlaceholder = nil
self.lblPlaceHolder.textColor = self.placeHolderColor
self.lblPlaceHolder.frame.origin.x = 0 ////\\
let fontSize = self.font!.pointSize;
self.lblPlaceHolder.font = UIFont.init(name: (self.font?.fontName)!, size: fontSize-3)
}
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {() -> Void in
if (self.text == nil) || (self.text?.count)! <= 0 {
self.lblPlaceHolder.font = self.defaultFont
self.lblPlaceHolder.frame = CGRect(x: self.lblPlaceHolder.frame.origin.x+10, y : 0, width :self.frame.size.width, height : self.frame.size.height)
}
else {
if self.directionMaterial == placeholderDirection.placeholderUp {
self.lblPlaceHolder.frame = CGRect(x : self.lblPlaceHolder.frame.origin.x, y : -self.difference, width : self.frame.size.width, height : self.frame.size.height)
}else{
self.lblPlaceHolder.frame = CGRect(x : self.lblPlaceHolder.frame.origin.x, y : self.difference, width : self.frame.size.width, height : self.frame.size.height)
}
}
}, completion: {(finished: Bool) -> Void in
})
}
}
func EnableMaterialPlaceHolder(enableMaterialPlaceHolder: Bool){
self.enableMaterialPlaceHolder = enableMaterialPlaceHolder
self.lblPlaceHolder = UILabel()
self.lblPlaceHolder.frame = CGRect(x: 0, y : 0, width : 0, height :self.frame.size.height)
self.lblPlaceHolder.font = UIFont.systemFont(ofSize: 10)
self.lblPlaceHolder.alpha = 0
self.lblPlaceHolder.clipsToBounds = true
self.addSubview(self.lblPlaceHolder)
self.lblPlaceHolder.attributedText = self.attributedPlaceholder
//self.lblPlaceHolder.sizeToFit()
}
func placeholderText(_ placeholder: NSString){
let atts = [NSAttributedString.Key.foregroundColor: UIColor.lightGray, NSAttributedString.Key.font: UIFont.labelFontSize] as [NSAttributedString.Key : Any]
self.attributedPlaceholder = NSAttributedString(string: placeholder as String , attributes:atts)
self.EnableMaterialPlaceHolder(enableMaterialPlaceHolder: self.enableMaterialPlaceHolder)
}
override public func becomeFirstResponder()->(Bool){
let returnValue = super.becomeFirstResponder()
return returnValue
}
override public func resignFirstResponder()->(Bool){
let returnValue = super.resignFirstResponder()
return returnValue
}
override public func layoutSubviews() {
super.layoutSubviews()
}
}
You can try using JSInputField which supports data validations as well.
JSInputField *inputField = [[JSInputField alloc] initWithFrame:CGRectMake(10, 100, 300, 50)];
[self.view addSubview:inputField];
[inputField setPlaceholder:#"Enter Text"];
[inputField setRoundedCorners:UIRectCornerAllCorners];
[inputField addValidationRule:JSCreateRuleNotNullValue]; //This will validate field for null value. It will show error if field is empty.
[inputField addValidationRule:JSCreateRuleNumeric(2)]; //This will validate field for numeric values and restrict to enter value upto 2 decimal places.
You can use SkyFloatingLabelTextField. It is SkyScanner's library for this kind of label or textField animations.
https://github.com/Skyscanner/SkyFloatingLabelTextField
I hope this answer will works for you.
Enjoy.
use this code
[your_textfieldname setShowsTouchWhenHighlighted:YES];

Resources