是否可以使视图控制器变暗(如警报视图控制器),除了该视图控制器的一个视图

时间:2018-02-22 06:18:03

标签: ios swift uiviewcontroller

我只想创建一个视图,当它显示时,整个背景将像警报视图控制器一样变暗。如果有可能请指导我,如果可能的话,请提供代码。

谢谢

2 个答案:

答案 0 :(得分:2)

最简单的方法是添加一个半透明背景(例如黑色,alpha小于1.0)视图,其中包含警报视图。后台视图应覆盖视图控制器中的所有其他视图。

您还可以使用具有此视图背景视图的模态视图控制器,并使用演示文稿样式 Over Full Screen 呈现此控制器。

答案 1 :(得分:1)

// Here is the wrapper code  i use in most of my project now a days
protocol TransparentBackgroundProtocol {

  associatedtype ContainedView
  var containedNib: ContainedView? { get set }

}

extension TransparentBackgroundProtocol  where ContainedView: UIView {

  func dismiss() {
    containedNib?.superview?.removeFromSuperview()
    containedNib?.removeFromSuperview()
  }

  mutating func add(withFrame frame: CGRect, toView view: UIView, backGroundViewAlpha: CGFloat) {
    containedNib?.frame = frame
    let backgroundView = configureABlackBackGroundView(alpha: backGroundViewAlpha)
    view.addSubview(backgroundView)

    guard let containedNib = containedNib else {
      print("No ContainedNib")
      return
    }
    backgroundView.addSubview(containedNib)
  }

  private func configureABlackBackGroundView(alpha: CGFloat) -> UIView {
    let blackBackgroundView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height))
    blackBackgroundView.backgroundColor = UIColor.black.withAlphaComponent(alpha)
    return blackBackgroundView
  }
}

// Sample View shown like alertView

class LogoutPopUpView: UIView, TransparentBackgroundProtocol {

    // MARK: Variables
    weak var containedNib: LogoutPopUpView?
    typealias ContainedView = LogoutPopUpView

    // MARK: Outlets


    // MARK: Functions
    class func initiate() -> LogoutPopUpView {
        guard let nibView = Bundle.main.loadNibNamed("LogoutPopUpView", owner: self, options: nil)?[0] as? LogoutPopUpView else {
            fatalError("Cann't able to load nib file.")
        }
         return nibView
    }

}


// where  u want to show pop Up
        logOutPopup = LogoutPopUpView.instanciateFromNib()
       let view = UIApplication.shared.keyWindow?.rootViewController?.view {
            logOutPopup?.add(withFrame: CGRect(x: 30, y:(UIScreen.main.bounds.size.height-340)/2, width: UIScreen.main.bounds.size.width - 60, height: 300), toView: view, backGroundViewAlpha: 0.8)            
        }
 // for dismiss
self.logOutPopup?.dismiss()