【问题标题】:Custom Alert in SwiftSwift 中的自定义警报
【发布时间】:2017-07-11 07:59:09
【问题描述】:

我一直在寻找自己制作自定义警报视图的时间。但是没有成功。我所做的是我在故事板的 xib 文件中设计一个视图并将其加载到应用程序中,但它只是像常规视图一样显示。我想要做的是使用 Swift 3 在 iOS >= 8 中将此视图呈现为 AlertController。我所做的是

let alert = Bundle.main.loadNibNamed("xib file to load", owner: self, options: nil)?.last as! UIView

// showAlert(alert: alert)
func showAlert(alert: UIView){
    let windows = UIApplication.shared.windows
    let lastWindow = windows.last
    print(lastWindow)
    alert.frame = CGRect(x: 0, y: 0, width: 150, height: 300)
    alert.center = self.view.center
    lastWindow?.addSubview(alert)
}

func removeAlert(alert: UIView){
    alert.removeFromSuperview()
}

这只是显示和隐藏视图。但我希望它像 UIAlertController 一样呈现。我希望背景中的所有内容都变暗,并且只关注这个视图。我怎样才能做到这一点。请帮我解决这个问题。

【问题讨论】:

标签: ios swift xcode uialertcontroller


【解决方案1】:

首先,您应该永远不要在 iOS 上触摸 window。极少数特殊情况除外。

您可以在 .xib 中创建具有透明或半透明背景的视图。然后你可以定义一个协议来呈现这个视图:

protocol AlertPresenting {}

extension AlertPresenting {
    func showAlert(_ onView: UIView) {
        if let alert = Bundle.main.loadNibNamed("AlertView", owner: nil, options: nil)![0] as? AlertView {
            alert.translatesAutoresizingMaskIntoConstraints = false

            onView.addSubview(alert)
            //here define constraints
            onView.bringSubviewToFront(alert)
        }
    }
}

然后你可以在任何viewController上使用它:

class MyViewController: UIViewController, AlertPresenting {
    func someFunction() {
        showAlert(onView: self.view)
    }
}

警报将首先出现在views

【讨论】:

  • 这个警报会像警报控制器吗?意味着背景中的所有内容都将变暗,并且警报看起来会略微升高?
  • @SalmanAli 您应该自己创建半透明背景,正如我在答案中所写。您自定义的alertView 应该覆盖整个屏幕,但非透明视图(您要显示的警报)应该更小。
【解决方案2】:
let alert = UIAlertController(title: "Record Inserted", message: 
"Record Inserted", preferredStyle: UIAlertController.Style.alert)

alert.addAction(UIAlertAction(title: "Ok", 
style:UIAlertAction.Style.default, handler: nil))

self.present(alert, animated: true, completion: nil)

【讨论】:

    【解决方案3】:

    在故事板中创建一个具有透明背景视图的视图控制器,然后呈现它

    let storyBoard = UIStoryboard(name: "Alert", bundle: .main)
    let viewController : UIViewController = storyBoard.instantiateViewController(withIdentifier: "AlertController")
    
    customAlertController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
    customAlertController.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
    
    self.present(customAlertController, animated: true, completion: nil)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多