ios - Swift 中的自定义警报

标签 ios swift xcode uialertcontroller

我一直在寻找自己制作自定义警报 View 的方法。但是没有成功。我所做的是在 Storyboard的 xib 文件中设计一个 View 并将其加载到应用程序中,但它只是像常规 View 一样显示。我想要做的是在 iOS >= 8 中使用 Swift 3 将此 View 作为 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()
}

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

最佳答案

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

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

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)
    }
}

警报将高于所有 View

关于ios - Swift 中的自定义警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45028664/

相关文章:

swift - 如何使用AVFoundation录制视频

ios - 安装发布和调试 iOS

ios - 线程1:EXC_BAD_ACCESS(代码= 2,地址= 0x7fff5450df68)

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

ios - Swift:通用类型符合协议(protocol)

xcode - 如何修复 "is a dynamic library, not added to the static library"警告?

ios - AVAssetWriter 元数据日期问题

ios - 每次应用程序启动时都会调用 WKWebView 请求 DeviceMotion 和 DeviceOrientation 的权限

ios - TestLab for iOS 中的 Flutter Integration 测试 - Use cases is not divided in iOS

string - 如何使用 Swift 修改字符串中的单个字符?