necesito insertar un botón flotante en la parte inferior derecha de la pantalla que funcione con swift 5, que sea compatible con iPhone y iPad.
Alguna información actualizada de cómo poder implementar esto en IOS 13, Xcode 11. Gracias.
Stack Overflow en español es un sitio de preguntas y respuestas para programadores y profesionales de la informática. Solo te toma un minuto registrarte.
Regístrate para unirte a esta comunidadnecesito insertar un botón flotante en la parte inferior derecha de la pantalla que funcione con swift 5, que sea compatible con iPhone y iPad.
Alguna información actualizada de cómo poder implementar esto en IOS 13, Xcode 11. Gracias.
Encontré una solucion que ha sido util para mí. Es bastante sencila de implementar y cumple con mis requerimientos:
La solución pasa por agregar los 2 archivos al proyecto (ActionButton.swift, ActionButtonItem.swift).
Archivo ActionButton.swift
import UIKit
public typealias ActionButtonAction = (ActionButton) -> Void
open class ActionButton: NSObject {
/// The action the button should perform when tapped
open var action: ActionButtonAction?
/// The button's background color : set default color and selected color
open var backgroundColor: UIColor = UIColor(red: 238.0/255.0, green: 130.0/255.0, blue: 34.0/255.0, alpha:1.0) {
willSet {
floatButton.backgroundColor = newValue
backgroundColorSelected = newValue
}
}
/// The button's background color : set default color
open var backgroundColorSelected: UIColor = UIColor(red: 238.0/255.0, green: 130.0/255.0, blue: 34.0/255.0, alpha:1.0)
/// Indicates if the buttons is active (showing its items)
fileprivate(set) open var active: Bool = false
/// An array of items that the button will present
internal var items: [ActionButtonItem]? {
willSet {
for abi in self.items! {
abi.view.removeFromSuperview()
}
}
didSet {
placeButtonItems()
showActive(true)
}
}
/// The button that will be presented to the user
fileprivate var floatButton: UIButton!
/// View that will hold the placement of the button's actions
fileprivate var contentView: UIView!
/// View where the *floatButton* will be displayed
fileprivate var parentView: UIView!
/// Blur effect that will be presented when the button is active
fileprivate var blurVisualEffect: UIVisualEffectView!
// Distance between each item action
fileprivate let itemOffset = -55
/// the float button's radius
fileprivate let floatButtonRadius = 50
public init(attachedToView view: UIView, items: [ActionButtonItem]?) {
super.init()
self.parentView = view
self.items = items
let bounds = self.parentView.bounds
self.floatButton = UIButton(type: .custom)
self.floatButton.layer.cornerRadius = CGFloat(floatButtonRadius / 2)
self.floatButton.layer.shadowOpacity = 1
self.floatButton.layer.shadowRadius = 2
self.floatButton.layer.shadowOffset = CGSize(width: 1, height: 1)
self.floatButton.layer.shadowColor = UIColor.gray.cgColor
self.floatButton.setTitle("+", for: UIControlState())
self.floatButton.setImage(nil, for: UIControlState())
self.floatButton.backgroundColor = self.backgroundColor
self.floatButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Light", size: 35)
self.floatButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 8, right: 0)
self.floatButton.isUserInteractionEnabled = true
self.floatButton.translatesAutoresizingMaskIntoConstraints = false
self.floatButton.addTarget(self, action: #selector(ActionButton.buttonTapped(_:)), for: .touchUpInside)
self.floatButton.addTarget(self, action: #selector(ActionButton.buttonTouchDown(_:)), for: .touchDown)
self.parentView.addSubview(self.floatButton)
self.contentView = UIView(frame: bounds)
self.blurVisualEffect = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight))
self.blurVisualEffect.frame = self.contentView.frame
self.contentView.addSubview(self.blurVisualEffect)
let tap = UITapGestureRecognizer(target: self, action: #selector(ActionButton.backgroundTapped(_:)))
self.contentView.addGestureRecognizer(tap)
self.installConstraints()
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - Set Methods
open func setTitle(_ title: String?, forState state: UIControlState) {
floatButton.setImage(nil, for: state)
floatButton.setTitle(title, for: state)
floatButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 8, right: 0)
}
open func setImage(_ image: UIImage?, forState state: UIControlState) {
setTitle(nil, forState: state)
floatButton.setImage(image, for: state)
floatButton.adjustsImageWhenHighlighted = false
floatButton.contentEdgeInsets = UIEdgeInsets.zero
}
//MARK: - Auto Layout Methods
/**
Install all the necessary constraints for the button. By the default the button will be placed at 15pts from the bottom and the 15pts from the right of its *parentView*
*/
fileprivate func installConstraints() {
let views: [String: UIView] = ["floatButton":self.floatButton, "parentView":self.parentView]
let width = NSLayoutConstraint.constraints(withVisualFormat: "H:[floatButton(\(floatButtonRadius))]", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: views)
let height = NSLayoutConstraint.constraints(withVisualFormat: "V:[floatButton(\(floatButtonRadius))]", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: views)
self.floatButton.addConstraints(width)
self.floatButton.addConstraints(height)
let trailingSpacing = NSLayoutConstraint.constraints(withVisualFormat: "V:[floatButton]-15-|", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: views)
let bottomSpacing = NSLayoutConstraint.constraints(withVisualFormat: "H:[floatButton]-15-|", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: views)
self.parentView.addConstraints(trailingSpacing)
self.parentView.addConstraints(bottomSpacing)
}
//MARK: - Button Actions Methods
@objc func buttonTapped(_ sender: UIControl) {
animatePressingWithScale(1.0)
if let unwrappedAction = self.action {
unwrappedAction(self)
}
}
@objc func buttonTouchDown(_ sender: UIButton) {
animatePressingWithScale(0.9)
}
//MARK: - Gesture Recognizer Methods
@objc func backgroundTapped(_ gesture: UIGestureRecognizer) {
if self.active {
self.toggle()
}
}
//MARK: - Custom Methods
/**
Presents or hides all the ActionButton's actions
*/
open func toggleMenu() {
self.placeButtonItems()
self.toggle()
}
//MARK: - Action Button Items Placement
/**
Defines the position of all the ActionButton's actions
*/
fileprivate func placeButtonItems() {
if let optionalItems = self.items {
for item in optionalItems {
item.view.center = CGPoint(x: self.floatButton.center.x - 83, y: self.floatButton.center.y)
item.view.removeFromSuperview()
self.contentView.addSubview(item.view)
}
}
}
//MARK - Float Menu Methods
/**
Presents or hides all the ActionButton's actions and changes the *active* state
*/
fileprivate func toggle() {
self.animateMenu()
self.showBlur()
self.active = !self.active
self.floatButton.backgroundColor = self.active ? backgroundColorSelected : backgroundColor
self.floatButton.isSelected = self.active
}
fileprivate func animateMenu() {
let rotation = self.active ? 0 : CGFloat(M_PI_4)
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.1, options: UIViewAnimationOptions.allowAnimatedContent, animations: {
if self.floatButton.imageView?.image == nil {
self.floatButton.transform = CGAffineTransform(rotationAngle: rotation)
}
self.showActive(false)
}, completion: {completed in
if self.active == false {
self.hideBlur()
}
})
}
fileprivate func showActive(_ active: Bool) {
if self.active == active {
self.contentView.alpha = 1.0
if let optionalItems = self.items {
for (index, item) in optionalItems.enumerated() {
let offset = index + 1
let translation = self.itemOffset * offset
item.view.transform = CGAffineTransform(translationX: 0, y: CGFloat(translation))
item.view.alpha = 1
}
}
} else {
self.contentView.alpha = 0.0
if let optionalItems = self.items {
for item in optionalItems {
item.view.transform = CGAffineTransform(translationX: 0, y: 0)
item.view.alpha = 0
}
}
}
}
fileprivate func showBlur() {
self.parentView.insertSubview(self.contentView, belowSubview: self.floatButton)
}
fileprivate func hideBlur() {
self.contentView.removeFromSuperview()
}
/**
Animates the button pressing, by the default this method just scales the button down when it's pressed and returns to its normal size when the button is no longer pressed
- parameter scale: how much the button should be scaled
*/
fileprivate func animatePressingWithScale(_ scale: CGFloat) {
UIView.animate(withDuration: 0.2, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.1, options: UIViewAnimationOptions.allowAnimatedContent, animations: {
self.floatButton.transform = CGAffineTransform(scaleX: scale, y: scale)
}, completion: nil)
}
}
Archivo ActionButtonItem.swift
import UIKit
public typealias ActionButtonItemAction = (ActionButtonItem) -> Void
open class ActionButtonItem: NSObject {
/// The action the item should perform when tapped
open var action: ActionButtonItemAction?
/// Description of the item's action
open var text: String {
get {
return self.label.text!
}
set {
self.label.text = newValue
}
}
/// View that will hold the item's button and label
internal var view: UIView!
/// Label that contain the item's *text*
fileprivate var label: UILabel!
/// Main button that will perform the defined action
fileprivate var button: UIButton!
/// Image used by the button
fileprivate var image: UIImage!
/// Size needed for the *view* property presente the item's content
fileprivate let viewSize = CGSize(width: 200, height: 35)
/// Button's size by default the button is 35x35
fileprivate let buttonSize = CGSize(width: 35, height: 35)
fileprivate var labelBackground: UIView!
fileprivate let backgroundInset = CGSize(width: 10, height: 10)
/**
:param: title Title that will be presented when the item is active
:param: image Item's image used by the it's button
*/
public init(title optionalTitle: String?, image: UIImage?) {
super.init()
self.view = UIView(frame: CGRect(origin: CGPoint.zero, size: self.viewSize))
self.view.alpha = 0
self.view.isUserInteractionEnabled = true
self.view.backgroundColor = UIColor.clear
self.button = UIButton(type: .custom)
self.button.frame = CGRect(origin: CGPoint(x: self.viewSize.width - self.buttonSize.width, y: 0), size: buttonSize)
self.button.layer.shadowOpacity = 1
self.button.layer.shadowRadius = 2
self.button.layer.shadowOffset = CGSize(width: 1, height: 1)
self.button.layer.shadowColor = UIColor.gray.cgColor
self.button.addTarget(self, action: #selector(ActionButtonItem.buttonPressed(_:)), for: .touchUpInside)
if let unwrappedImage = image {
self.button.setImage(unwrappedImage, for: UIControlState())
}
if let text = optionalTitle , text.trimmingCharacters(in: CharacterSet.whitespaces).isEmpty == false {
self.label = UILabel()
self.label.font = UIFont(name: "HelveticaNeue-Medium", size: 13)
self.label.textColor = UIColor.darkGray
self.label.textAlignment = .right
self.label.text = text
self.label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(ActionButtonItem.labelTapped(_:))))
self.label.sizeToFit()
self.labelBackground = UIView()
self.labelBackground.frame = self.label.frame
self.labelBackground.backgroundColor = UIColor.white
self.labelBackground.layer.cornerRadius = 3
self.labelBackground.layer.shadowOpacity = 0.8
self.labelBackground.layer.shadowOffset = CGSize(width: 0, height: 1)
self.labelBackground.layer.shadowRadius = 0.2
self.labelBackground.layer.shadowColor = UIColor.lightGray.cgColor
// Adjust the label's background inset
self.labelBackground.frame.size.width = self.label.frame.size.width + backgroundInset.width
self.labelBackground.frame.size.height = self.label.frame.size.height + backgroundInset.height
self.label.frame.origin.x = self.label.frame.origin.x + backgroundInset.width / 2
self.label.frame.origin.y = self.label.frame.origin.y + backgroundInset.height / 2
// Adjust label's background position
self.labelBackground.frame.origin.x = CGFloat(130 - self.label.frame.size.width)
self.labelBackground.center.y = self.view.center.y
self.labelBackground.addSubview(self.label)
// Add Tap Gestures Recognizer
let tap = UITapGestureRecognizer(target: self, action: #selector(ActionButtonItem.labelTapped(_:)))
self.view.addGestureRecognizer(tap)
self.view.addSubview(self.labelBackground)
}
self.view.addSubview(self.button)
}
//MARK: - Button Action Methods
@objc func buttonPressed(_ sender: UIButton) {
if let unwrappedAction = self.action {
unwrappedAction(self)
}
}
//MARK: - Gesture Recognizer Methods
@objc func labelTapped(_ gesture: UIGestureRecognizer) {
if let unwrappedAction = self.action {
unwrappedAction(self)
}
}
}
Luego en el ViewController se crea y configura el botón de la siguiente manera.
import UIKit
class ViewController: UIViewController {
var actionButton : ActionButton!
override func viewDidLoad() {
super.viewDidLoad()
setupButtons()
}
func setupButtons(){
let google = ActionButtonItem(title: "Google", image: UIImage .init(named: "nombre-de-mi-icono-google"))
google.action = { item in self.view.backgroundColor = UIColor.red }
let twitter = ActionButtonItem(title: "Twitter", image: UIImage .init(named: "nombre-de-mi-icono-twitter"))
twitter.action = { item in self.view.backgroundColor = UIColor.blue }
actionButton = ActionButton(attachedToView: self.view, items: [google, twitter])
actionButton.setTitle("+", forState: UIControlState())
actionButton.backgroundColor = UIColor(red: 238.0/255.0, green: 130.0/255.0, blue: 130.0/255.0, alpha: 1)
actionButton.action = { button in button.toggleMenu()}
}
}
Saludos.