LoginSignup
2
4

More than 5 years have passed since last update.

[iOS]フェードするポップアップビューを作成する!

Last updated at Posted at 2018-02-18

つくったもの

ポップアップ動作.mov.gif

・swift4使用

コード

PopupView.swift

import Foundation
import UIKit

public class PopupView {

    private var popupView: UIView!
    static let sharedManager = PopupView()

    private func setup() {
        popupView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
        popupView.backgroundColor = UIColor.gray
        popupView.alpha = 0.8
        popupView.layer.cornerRadius = 8

        // ポップアップ内のコンテンツを設定
        let labelWidth: CGFloat = 100
        let labelHeight: CGFloat = 100
        let labelItem = UILabel(frame: CGRect(x: popupView.frame.width/2.0 - labelWidth/2, y: popupView.frame.height/2.0 - labelHeight/2, width: labelWidth, height: labelHeight))
        labelItem.text = "✅"
        labelItem.font = UIFont(name:"Helvetica", size: 70.0)
        labelItem.textAlignment = NSTextAlignment.center
        popupView.addSubview(labelItem)
    }

    public func show() {
        if popupView == nil {
            self.setup()
        }

        if let window = UIApplication.shared.delegate?.window {
            window!.addSubview(popupView)
            popupView.center = window!.center
        }
    }

    public func hide() {
        UIView.animate(withDuration: 1, delay: 1, options: .curveEaseIn, animations: {
            self.popupView.alpha = 0
        }) { _ in
            self.popupView.removeFromSuperview()
            self.popupView.alpha = 1
        }
    }
}

使い方

表示したいタイミングで

PopupView.sharedManager.show()

隠すタイミングで

PopupView.sharedManager.hide()

以上😆!!

2
4
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
2
4