LoginSignup
1
1

Swiftで複数画面で使えるFloating Action Buttonを実装する

Posted at

はじめに

この記事はSwiftを使ってFloating Action Button(Xのような浮いてるボタン)を実装する方法を紹介します!Storyboardに直接おけばいいやん〜と思う方もいるかもしれないですが

  • 複数のViewControllerに同じボタンを置きたいとき
  • TableViewの上に重ねてボタンを置きたいとき

など、この記事で紹介するやり方が役にたつ場合もあることでしょう( ◠‿◠ )

環境

  • Xcode15.0.1
  • Swift5

完成図

開発の手順

ボタンを配置したView Conroller Classを作成し、このClassを他のView Controller Classで継承します。

1. 親Classの作成

普通にViewControllerを作る時と同じようにファイルを作成し、コードでボタンを配置します。長くなるのでsetupButtonとしてまとめました。これをViewDidLoadで呼び出します。

CommonUIViewController
import UIKit

class CommonUIViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupButton()
    }
    
    private func setupButton(){
        let button = UIButton(type: .system)
        let image = UIImage(systemName: "plus", withConfiguration: UIImage.SymbolConfiguration(pointSize: 32, weight: .bold))
        //↑"+"マークの大きさを調整している
        button.setImage(image, for: .normal) //ボタンの画像を"+"マークに指定
        button.tintColor = .white //ボタンの中にある"+"マークの色を指定
        button.backgroundColor = .black //ボタン自体の色を指定
        button.layer.cornerRadius = 30
        button.addTarget(self, action: #selector(commonButtonTapped), for: .touchUpInside)
        
        
        button.frame = CGRect(x: self.view.frame.size.width - 76, y: self.view.frame.size.height - 150, width: 60  , height: 60)
        self.view.addSubview(button)
    }

    //今回はボタンを押した時に新規投稿画面へ画面遷移するようにしています。
    @objc func commonButtonTapped(){
        let nextVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "AddTask") as! AddTaskViewController
        nextVC.modalPresentationStyle = .fullScreen
        self.present(nextVC, animated: true, completion: nil)
    }
    
}

コードでパーツを配置したことがなければこの記事が参考になります。

2. 子Classでの継承

継承するClassに先ほど作成した親Classを指定します。この時に注意するのが、もともと継承していたView Controllerは消すということです。
親ClassがすでにViewControllerを継承しているので同じクラスを2回継承することになり、エラーとなってしまいます!

OtherViewControllers
class CalendarViewController: CommonUIViewController {
    ...
}

これで、ボタンを配置したクラスを継承したViewControllerにはボタンが現れるようになります!

まとめ

継承できるClassとして作成することで複数の画面に同じボタンを配置できるだけでなく、タップした時の処理も統一できるのがいいですね!
これを機にStoryboardを使っている人もコードでのパーツ配置に挑戦してみましょう!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1