Im trying to implement a String list of messages to display on the screen for my login page. I need these messages to be able to scrolled through if the user decides to. I am using a label for my text. If the user does not scroll, then the messages will automatically scroll through. I tried using iCarousel but it does not achieve the effect I want.
You can use Libray https://github.com/cbpowell/MarqueeLabel
or easily you can also make auto scrollable label your own self like
func startAnimation()
{
//Animating the label automatically change as per your requirement
DispatchQueue.main.async(execute: {
UIView.animate(withDuration: 10.0, delay: 1, options: ([.curveLinear, .repeat]), animations: {
() -> Void in
self.demoLabel.center = CGPoint(x: 0 - self.demoLabel.bounds.size.width / 2, y: self.demoLabel.center.y)
}, completion: nil)
})
}
Usage
class ViewController: UIViewController {
let demoLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = .systemFont(ofSize: 14)
label.textColor = .green
label.text = "This is the demo label for testing automatically scrolling of uilabel when user not clicked on label if user click on label the scrolling is stoped."
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(demoLabel)
startAnimation()
}
Related
I have found lots of similar questions about not receiving touch events and I understand that in some cases, writing a custom hitTest function may be required - but I also read that the responder chain will traverse views and viewControllers that are in the hierarchy - and I don't understand why a custom hitTest would be required for my implementation.
I'm looking for an explanation and/or a link to a document that explains how to test the responder chain. This problem is occurring in Xcode 10.2.1.
My scenario (I am not using Storyboard):
I have a mainViewController, that provides a full screen view with an ImageView and a few Labels. I have attached TapGestureRecognizers to the ImageView and one of the labels - and they both work properly.
When I tap the label, I add a child viewController and it's view as a subview to the mainViewController. The view is constrained to cover only the right-half of the screen.
The child viewController contains a vertical stack view that contains 3 arrangedSubviews.
Each arrangedSubview contains a Label and a horizontal StackView.
The horizontal stackView's each contain a View with a Label as a subview.
The Label in the subview sets it's isUserInteractionEnabled flag to True and adds a TapGestureRecognizer.
These are the only objects in the child ViewController that have 'isUserInteractionEnabled' set.
The Label's are nested fairly deep, but since this is otherwise a direct parent/child hierarchy (as opposed to the 2 views belonging to a NavigationController), I would expect the Label's to be in the normal responder chain and function properly. Do the Stack View's change that behavior? Do I need to explicitly set the 'isUserInteractionEnabled' value to False on some of the views? Is there way I can add logging to the ResponderChain so I can see which views it checked and find out where it is being blocked?
After reading this StackOverflow post I tried adding my gesture recognizers in viewDidLayoutSubviews() instead of what's shown below - but they still do not receive tap events.
Thank you in advance to any who can offer advice or help.
Here is the code for the label that is not responding to my tap events and the tap event it should call:
func makeColorItem(colorName:String, bgColor:UIColor, fgColor:UIColor) -> UIView {
let colorNumber:Int = colorLabelDict.count
let colorView:UIView = {
let v = UIView()
v.tag = 700 + colorNumber
v.backgroundColor = .clear
v.contentMode = .center
return v
}()
self.view.addSubview(colorView)
let tapColorGR:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapColor))
let colorChoice: UILabel = {
let l = UILabel()
l.tag = 700 + colorNumber
l.isUserInteractionEnabled = true
l.addGestureRecognizer(tapColorGR)
l.text = colorName
l.textAlignment = .center
l.textColor = fgColor
l.backgroundColor = bgColor
l.font = UIFont.systemFont(ofSize: 24, weight: .bold)
l.layer.borderColor = fgColor.cgColor
l.layer.borderWidth = 1
l.layer.cornerRadius = 20
l.layer.masksToBounds = true
l.adjustsFontSizeToFitWidth = true
l.translatesAutoresizingMaskIntoConstraints = false
l.widthAnchor.constraint(equalToConstant: 100)
return l
}()
colorView.addSubview(colorChoice)
colorChoice.centerXAnchor.constraint(equalTo: colorView.centerXAnchor).isActive = true
colorChoice.centerYAnchor.constraint(equalTo: colorView.centerYAnchor).isActive = true
colorChoice.heightAnchor.constraint(equalToConstant: 50).isActive = true
colorChoice.widthAnchor.constraint(equalToConstant: 100).isActive = true
colorLabelDict[colorNumber] = colorChoice
return colorView
}
#objc func tapColor(sender:UITapGestureRecognizer) {
print("A Color was tapped...with tag:\(sender.view?.tag ?? -1)")
if let cn = sender.view?.tag {
colorNumber = cn
let v = colorLabelDict[cn]
if let l = (v?.subviews.first as? UILabel) {
print("The \(l.text) label was tapped.")
}
}
}
It looks like the main reason you're not getting a tap recognized is because you are adding a UILabel as a subview of a UIView, but you're not giving that UIView any constraints. So the view ends up with a width and height of Zero, and the label exists outside the bounds of the view.
Without seeing all of your code, it doesn't look like you need the extra view holding the label.
Take a look at this... it will add a vertical stack view to the main view - centered X and Y - and add "colorChoice" labels to the stack view:
class TestViewController: UIViewController {
let stack: UIStackView = {
let v = UIStackView()
v.axis = .vertical
v.spacing = 4
return v
}()
var colorLabelDict: [Int: UIView] = [:]
override func viewDidLoad() {
super.viewDidLoad()
let v1 = makeColorLabel(colorName: "red", bgColor: .red, fgColor: .white)
let v2 = makeColorLabel(colorName: "green", bgColor: .green, fgColor: .black)
let v3 = makeColorLabel(colorName: "blue", bgColor: .blue, fgColor: .white)
[v1, v2, v3].forEach {
stack.addArrangedSubview($0)
}
stack.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stack)
NSLayoutConstraint.activate([
stack.centerXAnchor.constraint(equalTo: view.centerXAnchor),
stack.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
}
func makeColorLabel(colorName:String, bgColor:UIColor, fgColor:UIColor) -> UILabel {
let colorNumber:Int = colorLabelDict.count
// create tap gesture recognizer
let tapColorGR:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapColor))
let colorChoice: UILabel = {
let l = UILabel()
l.tag = 700 + colorNumber
l.addGestureRecognizer(tapColorGR)
l.text = colorName
l.textAlignment = .center
l.textColor = fgColor
l.backgroundColor = bgColor
l.font = UIFont.systemFont(ofSize: 24, weight: .bold)
l.layer.borderColor = fgColor.cgColor
l.layer.borderWidth = 1
l.layer.cornerRadius = 20
l.layer.masksToBounds = true
l.adjustsFontSizeToFitWidth = true
l.translatesAutoresizingMaskIntoConstraints = false
// default .isUserInteractionEnabled for UILabel is false, so enable it
l.isUserInteractionEnabled = true
return l
}()
NSLayoutConstraint.activate([
// label height: 50, width: 100
colorChoice.heightAnchor.constraint(equalToConstant: 50),
colorChoice.widthAnchor.constraint(equalToConstant: 100),
])
// assign reference to this label in colorLabelDict dictionary
colorLabelDict[colorNumber] = colorChoice
// return newly created label
return colorChoice
}
#objc func tapColor(sender:UITapGestureRecognizer) {
print("A Color was tapped...with tag:\(sender.view?.tag ?? -1)")
// unwrap the view that was tapped, make sure it's a UILabel
guard let tappedView = sender.view as? UILabel else {
return
}
let cn = tappedView.tag
let colorNumber = cn
print("The \(tappedView.text ?? "No text") label was tapped.")
}
}
Result of running that:
Those are 3 UILabels, and tapping each will trigger the tapColor() func, printing this to the debug console:
A Color was tapped...with tag:700
The red label was tapped.
A Color was tapped...with tag:701
The green label was tapped.
A Color was tapped...with tag:702
The blue label was tapped.
FirebaseUI has a nice pre-buit UI for Swift. I'm trying to position an image view above the login buttons on the bottom. In the example below, the imageView is the "Hackathon" logo. Any logo should be able to show in this, if it's called "logo", since this shows the image as aspectFit.
According to the Firebase docs page:
https://firebase.google.com/docs/auth/ios/firebaseui
You can customize the signin screen with this function:
func authPickerViewController(forAuthUI authUI: FUIAuth) -> FUIAuthPickerViewController {
return FUICustomAuthPickerViewController(nibName: "FUICustomAuthPickerViewController",
bundle: Bundle.main,
authUI: authUI)
}
Using this code & poking around with subviews in the debuggers, I've been able to identify and color code views in the image below. Unfortunately, I don't think that the "true" size of these subview frames is set until the view controller presents, so trying to access the frame size inside these functions won't give me dimensions that I can use for creating a new imageView to hold a log. Plus accessing the views with hard-coded index values like I've done below, seems like a pretty bad idea, esp. given that Google has already changed the Pre-Built UI once, adding a scroll view & breaking the code of anyone who set the pre-built UI's background color.
func authPickerViewController(forAuthUI authUI: FUIAuth) -> FUIAuthPickerViewController {
// Create an instance of the FirebaseAuth login view controller
let loginViewController = FUIAuthPickerViewController(authUI: authUI)
// Set background color to white
loginViewController.view.backgroundColor = UIColor.white
loginViewController.view.subviews[0].backgroundColor = UIColor.blue
loginViewController.view.subviews[0].subviews[0].backgroundColor = UIColor.red
loginViewController.view.subviews[0].subviews[0].tag = 999
return loginViewController
}
I did get this to work by adding a tag (999), then in the completion handler when presenting the loginViewController I hunt down tag 999 and call a function to add an imageView with a logo:
present(loginViewController, animated: true) {
if let foundView = loginViewController.view.viewWithTag(999) {
let height = foundView.frame.height
print("FOUND HEIGHT: \(height)")
self.addLogo(loginViewController: loginViewController, height: height)
}
}
func addLogo(loginViewController: UINavigationController, height: CGFloat) {
let logoFrame = CGRect(x: 0 + logoInsets, y: self.view.safeAreaInsets.top + logoInsets, width: loginViewController.view.frame.width - (logoInsets * 2), height: self.view.frame.height - height - (logoInsets * 2))
// Create the UIImageView using the frame created above & add the "logo" image
let logoImageView = UIImageView(frame: logoFrame)
logoImageView.image = UIImage(named: "logo")
logoImageView.contentMode = .scaleAspectFit // Set imageView to Aspect Fit
// loginViewController.view.addSubview(logoImageView) // Add ImageView to the login controller's main view
loginViewController.view.addSubview(logoImageView)
}
But again, this doesn't seem safe. Is there a "safe" way to deconstruct this UI to identify the size of this button box at the bottom of the view controller (this size will vary if there are multiple login methods supported, such as Facebook, Apple, E-mail)? If I can do that in a way that avoids the hard-coding approach, above, then I think I can reliably use the dimensions of this button box to determine how much space is left in the rest of the view controller when adding an appropriately sized ImageView. Thanks!
John
This should address the issue - allowing a logo to be reliably placed above the prebuilt UI login buttons buttons + avoiding hard-coding the index values or subview locations. It should also allow for properly setting background color (also complicated when Firebase added the scroll view + login button subview).
To use: Create a subclass of FUIAuthDelegate to hold a custom view controller for the prebuilt Firebase UI.
The code will show the logo at full screen behind the buttons if there isn't a scroll view or if the class's private constant fullScreenLogo is set to false.
If both of these conditions aren't meant, the logo will show inset taking into account the class's private logoInsets constant and the safeAreaInsets. The scrollView views are set to clear so that a background image can be set, as well via the private let backgroundColor.
Call it in any signIn function you might have, after setting authUI.providers. Call would be something like this:
let loginViewController = CustomLoginScreen(authUI: authUI!)
let loginNavigationController = UINavigationController(rootViewController: loginViewController)
loginNavigationController.modalPresentationStyle = .fullScreen
present(loginNavigationController, animated: true, completion: nil)
And here's one version of the subclass:
class CustomLoginScreen: FUIAuthPickerViewController {
private var fullScreenLogo = false // false if you want logo just above login buttons
private var viewContainsButton = false
private var buttonViewHeight: CGFloat = 0.0
private let logoInsets: CGFloat = 16
private let backgroundColor = UIColor.white
private var scrollView: UIScrollView?
private var viewContainingButton: UIView?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// set color of scrollView and Button view inside scrollView to clear in viewWillAppear to avoid a "color flash" when the pre-built login UI first appears
self.view.backgroundColor = UIColor.white
guard let foundScrollView = returnScrollView() else {
print("😡 Couldn't get a scrollView.")
return
}
scrollView = foundScrollView
scrollView!.backgroundColor = UIColor.clear
guard let foundViewContainingButton = returnButtonView() else {
print("😡 No views in the scrollView contain buttons.")
return
}
viewContainingButton = foundViewContainingButton
viewContainingButton!.backgroundColor = UIColor.clear
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Create the UIImageView at full screen, considering logoInsets + safeAreaInsets
let x = logoInsets
let y = view.safeAreaInsets.top + logoInsets
let width = view.frame.width - (logoInsets * 2)
let height = view.frame.height - (view.safeAreaInsets.top + view.safeAreaInsets.bottom + (logoInsets * 2))
var frame = CGRect(x: x, y: y, width: width, height: height)
let logoImageView = UIImageView(frame: frame)
logoImageView.image = UIImage(named: "logo")
logoImageView.contentMode = .scaleAspectFit // Set imageView to Aspect Fit
logoImageView.alpha = 0.0
// Only proceed with customizing the pre-built UI if you found a scrollView or you don't want a full-screen logo.
guard scrollView != nil && !fullScreenLogo else {
print("No scrollView found.")
UIView.animate(withDuration: 0.25, animations: {logoImageView.alpha = 1.0})
self.view.addSubview(logoImageView)
self.view.sendSubviewToBack(logoImageView) // otherwise logo is on top of buttons
return
}
// update the logoImageView's frame height to subtract the height of the subview containing buttons. This way the buttons won't be on top of the logoImageView
frame = CGRect(x: x, y: y, width: width, height: height - (viewContainingButton?.frame.height ?? 0.0))
logoImageView.frame = frame
self.view.addSubview(logoImageView)
UIView.animate(withDuration: 0.25, animations: {logoImageView.alpha = 1.0})
}
private func returnScrollView() -> UIScrollView? {
var scrollViewToReturn: UIScrollView?
if self.view.subviews.count > 0 {
for subview in self.view.subviews {
if subview is UIScrollView {
scrollViewToReturn = subview as? UIScrollView
}
}
}
return scrollViewToReturn
}
private func returnButtonView() -> UIView? {
var viewContainingButton: UIView?
for view in scrollView!.subviews {
viewHasButton(view)
if viewContainsButton {
viewContainingButton = view
break
}
}
return viewContainingButton
}
private func viewHasButton(_ view: UIView) {
if view is UIButton {
viewContainsButton = true
} else if view.subviews.count > 0 {
view.subviews.forEach({viewHasButton($0)})
}
}
}
Hope this helps any who have been frustrated trying to configure the Firebase pre-built UI in Swift.
I am trying to re-create a Facebook sign up page for practice; the set up of my viewController is as follows:
1)A profile image container at the top,
2)Email textfield
3)Password Textfield
4)Confirm Password textfield
To solve the issue of the keyboard blocking the "Confirm Password" field, I have used listeners as below.
The issue is that the very first time a user clicks on a textfield to type (no matter which one), the screen moves way too far up, such that the email textfield at the top ends up going beyond the screen size on top. However, when I dismiss the keyboard and re-click on any textfield, it goes up as intended: Only until the top textfield reaches the top of the screen.
I can find no other reason for this behaviour, it persisted even after I re-wrote some of my code.
My ViewController set up:
class ViewController: UIViewController {
#objc func dismissKeyboard() {
view.endEditing(true)
}
let imageContainer: UIView = {
let v = UIView()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .red
return v
}()
let emailTF: UITextField = {
let tf = UITextField()
tf.translatesAutoresizingMaskIntoConstraints = false
tf.placeholder = "EMAIL"
return tf
}()
let passwordTF: UITextField = {
let tf = UITextField()
tf.translatesAutoresizingMaskIntoConstraints = false
tf.placeholder = "Password"
return tf
}()
let confirmPasswordTF: UITextField = {
let tf = UITextField()
tf.translatesAutoresizingMaskIntoConstraints = false
tf.placeholder = "Confirm password"
return tf
}()
#objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0 {
self.view.frame.origin.y -= keyboardSize.height
}
}
}
#objc func keyboardWillHide(notification: NSNotification) {
if self.view.frame.origin.y != 0 {
self.view.frame.origin.y = 0
}
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .lightGray
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
view.addSubview(imageContainer)
view.addSubview(emailTF)
view.addSubview(passwordTF)
view.addSubview(confirmPasswordTF)
NSLayoutConstraint.activate([
imageContainer.centerXAnchor.constraint(equalTo: view.centerXAnchor),
imageContainer.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.275),
imageContainer.widthAnchor.constraint(equalTo: view.heightAnchor),
imageContainer.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
emailTF.topAnchor.constraint(equalTo: imageContainer.bottomAnchor),
emailTF.heightAnchor.constraint(equalToConstant: 100),
emailTF.widthAnchor.constraint(equalToConstant: 200),
emailTF.centerXAnchor.constraint(equalTo: view.centerXAnchor),
passwordTF.topAnchor.constraint(equalTo: emailTF.bottomAnchor, constant: 20),
passwordTF.heightAnchor.constraint(equalToConstant: 100),
passwordTF.widthAnchor.constraint(equalToConstant: 200),
passwordTF.centerXAnchor.constraint(equalTo: view.centerXAnchor),
confirmPasswordTF.topAnchor.constraint(equalTo: passwordTF.bottomAnchor, constant: 20),
confirmPasswordTF.heightAnchor.constraint(equalToConstant: 100),
confirmPasswordTF.widthAnchor.constraint(equalToConstant: 200),
confirmPasswordTF.centerXAnchor.constraint(equalTo: view.centerXAnchor),
])
let tapToDismissKeyboard: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
view.addGestureRecognizer(tapToDismissKeyboard)
}
}
I'd really appreciate some help as to what I can do to correct this issue.
Seems like this is a known issue raised here and other SO questions too..
Two points to make:-
1) Use UIResponder.keyboardFrameEndUserInfoKey instead of UIResponder.keyboardFrameBeginUserInfoKey at:
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
in keyboardWillShow()
2) Doing so, you will get the total height of the keyboard including the toolbar. Which means:
However, when I dismiss the keyboard and re-click on any textfield, it
goes up as intended: Only until the top textfield reaches the top of
the screen.
This is the buggy behaviour where you get an incorrect height excluding the toolbar and:
The issue is that the very first time a user clicks on a textfield to
type (no matter which one), the screen moves way too far up, such that
the email textfield at the top ends up going beyond the screen size on
top.
This is actually the intended behaviour with actual height. You could calculate the height of the toolbar and reduce it from this height to achieve your goal! If your VC is embedded in a navigation controller, you could use this
Hope this helps.
i have 3 UITextField. when i set the resignFirstResponder for the text field, for every key press the key board goes down and key board pops up when we enter. which means for each letter pressed the key board disappears
I tried creating an outlet for the text field as below but the print statement is executed but the key board is not getting disappeared when focus lost or moved to the next text field
#IBAction func done(_ sender: UITextField) {
print("Text field done$$$$$$$$$$$$$$$")
sender.endEditing(true)
sender.resignFirstResponder()
// print("After Resign")
}
tried the below one also:
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))))
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
//Textfield
let textfield = UITextField()
textfield.setShadowTextField(username, "user-name")
textfield.setShadowTextField(useremail, "email")
textfield.setShadowTextField(userPhone, "phone")
//Hide Keyboard
textName.resignFirstResponder()
textEmail.resignFirstResponder()
userPhone.resignFirstResponder()
//
name = textName.text ?? ""
emailphone = textEmail.text ?? ""
//Button
if isFirstTimeSubView == true {
button?.setSemiButtonLeft(btnFemaleSelector, shadowViewFemale)
button?.setGradientButton(btnFemaleSelector, startColor: "0d5e90", endColor: "8ec67d")
button?.setSemiButtonRight(btnMaleSelector, shadowViewMale)
button?.setGradientButton(btnMaleSelector, startColor: "FFFFFF", endColor: "FFFFFF")
isFirstTimeSubView = false
}
button?.setRoundButton(btnSubmit, shadowView)
button?.setGradientButton(btnSubmit, startColor: "0d5e90", endColor: "8ec67d")
//textNam.sendAction("resignFirstResponder", to:nil, from:nil, forEvent:nil)
// self.userText.delegate = selftextName.resignFirstResponder()
}
extension UITextField {
func setShadowTextField(_ textfield: UITextField?, _ imagename: String?) {
// set color & border
textfield?.borderStyle = .none
textfield?.backgroundColor = UIColor.white
// set corner
textfield?.layer.cornerRadius = (textfield?.frame.size.height ?? 0.0) / 2
//set shadow
textfield?.layer.shadowOpacity = 0.4
textfield?.layer.shadowRadius = 15
textfield?.layer.shadowOffset = CGSize(width: 5, height: 10)
textfield?.layer.shadowColor = UIColor.gray.cgColor
// set icon & Placeholder position
let UIViewController = UIView(frame: CGRect(x: 0, y: 0, width: 60, height: textfield?.frame.size.height ?? 0.0))
let icon = UIImageView(image: UIImage(named: imagename ?? ""))
icon.frame = CGRect(x: 0, y: 0, width: UIViewController.frame.size.width / 4, height: UIViewController.frame.size.height / 4)
icon.center = UIViewController.center
UIViewController.addSubview(icon)
textfield?.leftView = UIViewController
textfield?.leftViewMode = .always
}
}
The question is a little unclear but if you want the keyboard to go down when you've pressed the done button, you should implement the UITextFieldDelegate on your view controller and during the textFieldShouldReturn(_:) method call resignFirstResponder from there:
class myVC: UIViewController, UITextFieldDelegate{
func textFieldShouldReturn(_ textField: UITextField) -> Bool{
return true
}
}
and don't forget to set the delegate in the viewDidLoad for your VC:
override func viewDidLoad() {
super.viewDidLoad()
/// Text field delegate handling
textFieldFirstName.delegate = self
}
https://developer.apple.com/documentation/uikit/uitextfielddelegate/1619603-textfieldshouldreturn?language=objc
By calling resignFirstResponder in viewDidLayoutSubviews, you are resigning the responder every time the viewDidLayoutSubviews is called, i.e. When the bounds change for a view controller's view, the view adjusts the positions of its subviews and then the system calls this method. So I presume the keyboard will be changing the bounds, causing viewDidLayoutSubviews to fire after each keypress and creating the behaviour you are seeing
Here is my code. I am using KeyboardHelper library for managing keyboard states and getting keyboard height, and also SnapKit. I have a text field that triggers keyboard. When a keyboard is visible I want to raise blue box above keyboard bounds, so it's visible. So far I failed to do so. Can you please help me with my code?
private var keyboardHelper : KeyboardHelper?
let box = UIView()
override func viewDidLoad() {
super.viewDidLoad()
keyboardHelper = KeyboardHelper(delegate: self)
guard let superview = self.view else {
return
}
box.backgroundColor = UIColor.blue
superview.addSubview(box)
box.snp.makeConstraints { make in
make.bottom.equalTo(superview.snp.bottom).offset(-16)
make.width.equalTo(200)
make.centerX.equalTo(superview)
make.height.equalTo(100)
}
}
func keyboardWillAppear(_ info: KeyboardAppearanceInfo) {
UIView.animate(withDuration: TimeInterval(info.animationDuration), delay: 0, options: info.animationOptions, animations: {
self.box.snp.updateConstraints({ make in
make.bottom.equalTo(info.endFrame.size.height).offset(10)
})
self.box.layoutIfNeeded()
}, completion: nil)
}
According to SnapKit docs:
if you are only updating the constant value of the constraint you can use the method snp.updateConstraints
You need to use snp.remakeConstraints in your case. Furthermore, you should probably call layoutIfNeeded on superview.
Optionally you could get rid of changing constraints and just animate proper transforms on show:
box.transform = CGAffineTransform(translationX: 0.0, y: neededTranslation)
on hide:
box.transform = .identity