swiftuikitfloating-action-buttonapple-maps

How do you make floating buttons like the ones in Apple Maps?


I want to know how to make floating action buttons like the ones in Apple Maps using UIKit. I'm specifically stuck on recreating the behavior where the buttons' offset changes dynamically as the height of the half sheet changes.

I'm presenting the half sheet by setting the parent view controller's sheetPresentationController to my child view controller. I've overridden the child's viewWillLayoutSubviews to get its view's new height, and then I set the floating buttons' offset accordingly.

However, I'm running into an issue where the buttons' offset "jumps" if the user lets go of the sheet early. I noticed that when the user lets go early, the view's height could jump from 200 to 500, for example. This is undesired because I'd prefer the buttons' offset to appear to change smoothly like in Apple Maps. Is there a way to get more granular updates to the child's height?

Here is a gif showcasing the behavior in Apple Maps:

enter image description here

Here is a gif showing the "jumping behavior" in my sample project:

enter image description here

Here is the code from a simplified sample project:

class ViewController: UIViewController {
  private var subscriptions = Set<AnyCancellable>()
  private var buttonBottomConstraint = NSLayoutConstraint()
  
  private lazy var floatingButton: UIButton = {
    let button = UIButton()
    
    button.setImage(
      UIImage(systemName: "list.dash"), for: .normal
    )
    
    button.addTarget(
      self,
      action: #selector(openSheet),
      for: .touchUpInside
    )
    
    button.translatesAutoresizingMaskIntoConstraints = false
    button.backgroundColor = .systemBackground.withAlphaComponent(0.95)
    button.layer.cornerRadius = 20.0
    button.layer.shadowColor = UIColor.black.cgColor
    button.layer.shadowOpacity = 0.5
    button.layer.shadowOffset = CGSize(width: 0, height: 2)
    button.layer.shadowRadius = 4.0
    button.layer.shouldRasterize = true
    button.layer.rasterizationScale = UIScreen.main.scale
    return button
  }()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    configureView()
  }
  
  private func configureView() {
    view.backgroundColor = .systemMint
    view.addSubview(floatingButton)
    
    buttonBottomConstraint = floatingButton.bottomAnchor.constraint(
      equalTo: view.bottomAnchor,
      constant: -100
    )
        
    NSLayoutConstraint.activate([
      buttonBottomConstraint,
      floatingButton.trailingAnchor.constraint(
        equalTo: view.trailingAnchor,
        constant: -10
      ),
      floatingButton.heightAnchor.constraint(equalToConstant: 50),
      floatingButton.widthAnchor.constraint(equalToConstant: 50)
    ])
  }
  
  @objc
  private func openSheet() {
    let childViewController = ChildViewController()
    configureChildViewControllerFrameSubscription(childViewController)
    
    if let sheet = childViewController.sheetPresentationController {
      sheet.detents = [.small(), .medium(), .large()]
      sheet.largestUndimmedDetentIdentifier = .medium
      sheet.prefersGrabberVisible = true
    }
    
    childViewController.isModalInPresentation = true
    present(childViewController, animated: true)
  }
}

extension ViewController {
  private func configureChildViewControllerFrameSubscription(
    _ childViewController: ChildViewController
  ) {
    childViewController.framePassthroughSubject
      .receive(on: DispatchQueue.main)
      .sink { frame in
        self.buttonBottomConstraint.isActive = false
        
        self.buttonBottomConstraint = self.floatingButton.bottomAnchor.constraint(
          equalTo: self.view.bottomAnchor,
          constant: (frame.height * -1) - 10
        )
        
        self.buttonBottomConstraint.isActive = true
        self.floatingButton.layoutIfNeeded()
      }
      .store(in: &subscriptions)
  }
}

extension UISheetPresentationController.Detent.Identifier {
  static var smallIdentifier: Self {
    Self("small")
  }
}

extension UISheetPresentationController.Detent {
  static func small() -> UISheetPresentationController.Detent {
    .custom(identifier: .smallIdentifier) { context in
      context.maximumDetentValue * 0.15
    }
  }
}

class ChildViewController: UIViewController {
  let framePassthroughSubject = PassthroughSubject<CGRect, Never>()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    view.backgroundColor = .systemBlue
  }
  
  override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()
    framePassthroughSubject.send(view.frame)
  }
}

Solution

  • Yes, the viewDidLayoutSubviews pattern will not gracefully handle an animation once the user lets go. (It doesn’t really handle any animations well.) It will frequently result in this jarring “jump to final location” sort of UI. Bottom line, we want to avoid updating the button location manually and instead let the layout system do this for us.

    For example, we can solve this (and simplify this greatly) by adding a constraint between the button to this new subview (and I will animate it into place):

    present(childViewController, animated: true) { [self] in
        UIView.animate(withDuration: 0.25) { 
            childViewController.view.topAnchor.constraint(
                equalTo: floatingButton.bottomAnchor, 
                constant: 10
            ).isActive = true
            floatingButton.layoutIfNeeded()
        }
    }
    

    Obviously, we will want to reduce the priority of the existing constraint between the button to the main view, so that it can gracefully prioritize this new constraint, thereby avoiding conflicting constraints:

    let buttonBottomConstraint = floatingButton.bottomAnchor.constraint(
        equalTo: view.bottomAnchor,
        constant: -10
    )
    buttonBottomConstraint.priority = .defaultHigh // rather than the default of .required
    
    NSLayoutConstraint.activate([
        buttonBottomConstraint,
        floatingButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
        floatingButton.heightAnchor.constraint(equalToConstant: 50),
        floatingButton.widthAnchor.constraint(equalToConstant: 50)
    ])
    

    That will let the constraints system use this buttonBottomConstraint before the child view is presented, but let the new constraint take priority once the child appears.

    (As an aside, as we are going to let the constraints system handle all of this for you, buttonBottomConstraint no longer needs to be a property, but can just be a local variable.)

    Anyway, once you do that, you can (and should) eliminate all of the Combine code that was manually updating the frame.

    The constraints system will take care of pinning that button to the subview, seamlessly keeping the button a fixed distance from the child view as the user drags the child view height, as well as when they let go of it and it animates to some final location. It also solves the lagginess of the button location as the user drags the child view handle, too.


    FWIW, here is my final rendition of your MRE:

    class ViewController: UIViewController {
        private lazy var floatingButton: UIButton = {
            let button = UIButton()
    
            button.setImage(
                UIImage(systemName: "list.dash"), for: .normal
            )
    
            button.addTarget(
                self,
                action: #selector(openSheet),
                for: .touchUpInside
            )
    
            button.translatesAutoresizingMaskIntoConstraints = false
            button.backgroundColor = .systemBackground.withAlphaComponent(0.95)
            button.layer.cornerRadius = 20.0
            button.layer.shadowColor = UIColor.black.cgColor
            button.layer.shadowOpacity = 0.5
            button.layer.shadowOffset = CGSize(width: 0, height: 2)
            button.layer.shadowRadius = 4.0
            button.layer.shouldRasterize = true
            button.layer.rasterizationScale = UIScreen.main.scale
            return button
        }()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            configureView()
        }
    
        private func configureView() {
            view.backgroundColor = .systemMint
            view.addSubview(floatingButton)
    
            let buttonBottomConstraint = floatingButton.bottomAnchor.constraint(
                equalTo: view.bottomAnchor,
                constant: -10
            )
            buttonBottomConstraint.priority = .defaultHigh
    
            NSLayoutConstraint.activate([
                buttonBottomConstraint,
                floatingButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
                floatingButton.heightAnchor.constraint(equalToConstant: 50),
                floatingButton.widthAnchor.constraint(equalToConstant: 50)
            ])
        }
    
        @objc
        private func openSheet() {
            let childViewController = ChildViewController()
    
            if let sheet = childViewController.sheetPresentationController {
                sheet.detents = [.small(), .medium(), .large()]
                sheet.largestUndimmedDetentIdentifier = .medium
                sheet.prefersGrabberVisible = true
            }
    
            childViewController.isModalInPresentation = true
            childViewController.animateAlongside = { [self] _ in
                NSLayoutConstraint.activate([
                    childViewController.view.topAnchor.constraint(equalTo: floatingButton.bottomAnchor, constant: 10)
                ])
    
                view.layoutIfNeeded()
            }
            present(childViewController, animated: true)
        }
    }
    
    extension UISheetPresentationController.Detent.Identifier {
        static var smallIdentifier: Self {
            Self("small")
        }
    }
    
    extension UISheetPresentationController.Detent {
        static func small() -> UISheetPresentationController.Detent {
            .custom(identifier: .smallIdentifier) { context in
                context.maximumDetentValue * 0.15
            }
        }
    }
    
    class ChildViewController: UIViewController {
        var animateAlongside: ((any UIViewControllerTransitionCoordinatorContext) -> Void)?
    
        override func viewDidLoad() {
            super.viewDidLoad()
            view.backgroundColor = .systemBlue
        }
    
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
    
            transitionCoordinator?.animate(alongsideTransition: { [self] context in
                animateAlongside?(context)
                animateAlongside = nil
            })
        }
    }
    

    That results in:

    enter image description here