Подтвердить что ты не робот

Swift: кнопка Floating Plus через Tableview с использованием StoryBoard

Как добавить плавающую кнопку в Facebook App Rooms с помощью раскадровки?

Я не могу перетащить UIView на просмотр таблицы, что я знаю только так.

enter image description here enter image description here

4b9b3361

Ответ 1

Код этой кнопки ниже:

  • Добавляет тень
  • Делает кнопку круглой
  • Добавляет анимацию, чтобы привлечь внимание

Swift 4.2: ПОЛНАЯ РЕАЛИЗАЦИЯ КОНТРОЛЛЕРА

import Foundation

public class FloatingButtonViewController: UIViewController {
    private var floatingButton: UIButton?
    // TODO: Replace image name with your own image:
    private let floatingButtonImageName = "NAME OF YOUR IMAGE"
    private static let buttonHeight: CGFloat = 75.0
    private static let buttonWidth: CGFloat = 75.0
    private let roundValue = FloatingButtonViewController.buttonHeight/2
    private let trailingValue: CGFloat = 15.0
    private let leadingValue: CGFloat = 15.0
    private let shadowRadius: CGFloat = 2.0
    private let shadowOpacity: Float = 0.5
    private let shadowOffset = CGSize(width: 0.0, height: 5.0)
    private let scaleKeyPath = "scale"
    private let animationKeyPath = "transform.scale"
    private let animationDuration: CFTimeInterval = 0.4
    private let animateFromValue: CGFloat = 1.00
    private let animateToValue: CGFloat = 1.05

    public override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        createFloatingButton()
    }

    public override func viewWillDisappear(_ animated: Bool) {
        guard floatingButton?.superview != nil else {  return }
        DispatchQueue.main.async {
            self.floatingButton?.removeFromSuperview()
            self.floatingButton = nil
        }
        super.viewWillDisappear(animated)
    }

    private func createFloatingButton() {
        floatingButton = UIButton(type: .custom)
        floatingButton?.translatesAutoresizingMaskIntoConstraints = false
        floatingButton?.backgroundColor = .white
        floatingButton?.setImage(UIImage(named: floatingButtonImageName), for: .normal)
        floatingButton?.addTarget(self, action: #selector(doThisWhenButtonIsTapped(_:)), for: .touchUpInside)
        constrainFloatingButtonToWindow()
        makeFloatingButtonRound()
        addShadowToFloatingButton()
        addScaleAnimationToFloatingButton()
    }

    // TODO: Add some logic for when the button is tapped.
    @IBAction private func doThisWhenButtonIsTapped(_ sender: Any) {
        print("Button Tapped")
    }

    private func constrainFloatingButtonToWindow() {
        DispatchQueue.main.async {
            guard let keyWindow = UIApplication.shared.keyWindow,
                let floatingButton = self.floatingButton else { return }
            keyWindow.addSubview(floatingButton)
            keyWindow.trailingAnchor.constraint(equalTo: floatingButton.trailingAnchor,
                                                constant: self.trailingValue).isActive = true
            keyWindow.bottomAnchor.constraint(equalTo: floatingButton.bottomAnchor,
                                              constant: self.leadingValue).isActive = true
            floatingButton.widthAnchor.constraint(equalToConstant:
                FloatingButtonViewController.buttonWidth).isActive = true
            floatingButton.heightAnchor.constraint(equalToConstant:
                FloatingButtonViewController.buttonHeight).isActive = true
        }
    }

    private func makeFloatingButtonRound() {
        floatingButton?.layer.cornerRadius = roundValue
    }

    private func addShadowToFloatingButton() {
        floatingButton?.layer.shadowColor = UIColor.black.cgColor
        floatingButton?.layer.shadowOffset = shadowOffset
        floatingButton?.layer.masksToBounds = false
        floatingButton?.layer.shadowRadius = shadowRadius
        floatingButton?.layer.shadowOpacity = shadowOpacity
    }

    private func addScaleAnimationToFloatingButton() {
        // Add a pulsing animation to draw attention to button:
        DispatchQueue.main.async {
            let scaleAnimation: CABasicAnimation = CABasicAnimation(keyPath: self.animationKeyPath)
            scaleAnimation.duration = self.animationDuration
            scaleAnimation.repeatCount = .greatestFiniteMagnitude
            scaleAnimation.autoreverses = true
            scaleAnimation.fromValue = self.animateFromValue
            scaleAnimation.toValue = self.animateToValue
            self.floatingButton?.layer.add(scaleAnimation, forKey: self.scaleKeyPath)
        }
    }
}

Ответ 2

Немного поздно, но может быть, это может помочь кому-то. Вы можете сделать это очень легко с помощью программной программы. Просто создайте экземпляр кнопки, установите желаемое свойство кнопки. Предпочтительно use constraints over frame заставить отображать кнопку в той же позиции на каждом размере экрана. Я отправляю код, который сделает кнопку круглой. Играйте со значением ограничений, чтобы изменить положение и размер кнопки.

Swift 3

var roundButton = UIButton()
override func viewDidLoad() {
    super.viewDidLoad()
    self.roundButton = UIButton(type: .custom)
    self.roundButton.setTitleColor(UIColor.orange, for: .normal)
    self.roundButton.addTarget(self, action: #selector(ButtonClick(_:)), for: UIControlEvents.touchUpInside)
    self.view.addSubview(roundButton)
}

override func viewWillLayoutSubviews() {

    roundButton.layer.cornerRadius = roundButton.layer.frame.size.width/2
    roundButton.backgroundColor = UIColor.lightGray
    roundButton.clipsToBounds = true
    roundButton.setImage(UIImage(named:"your-image"), for: .normal)
    roundButton.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        roundButton.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -3),  
    roundButton.bottomAnchor.constraint  
    (equalTo: self.view.bottomAnchor, constant: -53), 
    roundButton.widthAnchor.constraint(equalToConstant: 50),
    roundButton.heightAnchor.constraint(equalToConstant: 50)])
}

/** Action Handler for button **/

@IBAction func ButtonClick(_ sender: UIButton){

 /** Do whatever you wanna do on button click**/

}

Ответ 3

Поместите табличное представление в контроллере представления. После этого вы сможете добавить кнопку в верхней части представления таблицы.

Storyboard

Ответ 4

Следуя ответу @Кунал Кумар, он работает с UIScrollView и UIView, но он не работает на UITableView. Я нашел, что легко работать с UITableView, нужно только добавить один код строки. Большое вам спасибо @Kunal Kumar

в viewDidLoad, измените self.view.addSubview(roundButton) на self.navigationController?.view.addSubview(roundButton) и он будет работать!

Кстати, я думаю, нам нужно добавить super.viewWillLayoutSubviews() в метод viewWillLayoutSubviews().

ниже приведен весь код, упомянутый выше,

Swift 3

// MARK: Floating Button

var roundButton = UIButton()
func createFloatingButton() {
    self.roundButton = UIButton(type: .custom)
    self.roundButton.setTitleColor(UIColor.orange, for: .normal)
    self.roundButton.addTarget(self, action: #selector(ButtonClick(_:)), for: UIControlEvents.touchUpInside)
    //change view to navigationController?.view, if you have a navigationController in this tableview
    self.navigationController?.view.addSubview(roundButton)
}

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()

    roundButton.layer.cornerRadius = roundButton.layer.frame.size.width/2
    roundButton.backgroundColor = UIColor.lightGray
    roundButton.clipsToBounds = true
    roundButton.setImage(UIImage(named:"ic_wb_sunny_48pt"), for: .normal)
    roundButton.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        roundButton.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -3),
        roundButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -53),
        roundButton.widthAnchor.constraint(equalToConstant: 50),
        roundButton.heightAnchor.constraint(equalToConstant: 50)])
}

Ответ 5

Это просто потому, что ваша UIButton находится под UITableView, переместите его в дерево раскадровки, чтобы он выглядел так:

| View
|-- Table View
|-- Button