ios – 带有swift的自定义警报(UIAlertView)

如何使用 Swift创建自定义警报?我尝试从Objective c翻译指南但加载全屏布局

为了方便我可以加载透明背景的新布局我试试这个:

listaalertviewcontroller.view.backgroundColor = UIColor.clearColor()
    let purple = UIColor.purpleColor() // 1.0 alpha
    let semi = purple.colorWithAlphaComponent(0.5)

    listaalertviewcontroller.view.backgroundColor = semi


    presentingViewController.modalPresentationStyle = UIModalPresentationStyle.CurrentContext

    self.presentViewController(listaalertviewcontroller,animated: true,completion: nil)

在动画中它是透明的,但是当动画结束时它是不透明的……我在视图中关闭了不透明的选项……我做错了什么?

解决方法

代码在Swift 5和Xcode 10中测试过

如何制作自己的自定义提醒

我想做类似的事情.首先,UIAlertView不赞成使用UIAlertController.有关显示警报的标准方法,请参阅此答案:

> How would I create a UIAlertView in Swift?

UIAlertView和UIAlertController都不能真正实现太多自定义.一种选择是使用一些第三方代码.但是,我发现通过显示另一个视图控制器modaly创建自己的警报并不困难.

这里的例子只是一个概念验证.您可以按照自己的方式设计警报.

enter image description here

故事板

你应该有两个视图控制器.您的第二个视图控制器将是您的警报.将类名设置为AlertViewContoller,并将Storyboard ID设置为警报. (这些都是我们在下面的代码中定义的名称,没有什么特别之处.如果需要,可以先添加代码.如果先添加代码,实际上可能会更容易.)

enter image description here

将根视图(在警报视图控制器中)的背景颜色设置为清除(或半透明黑色适用于警报).添加另一个UIView并使用约束来居中.使用它作为你的警报背景,并把你想要的东西放在里面.在我的例子中,我添加了一个UIButton.

enter image description here

ViewController.swift

import UIKit
class ViewController: UIViewController {

    @IBAction func showAlertButtonTapped(_ sender: UIButton) {

        let storyboard = UIStoryboard(name: "Main",bundle: nil)
        let myAlert = storyboard.instantiateViewController(withIdentifier: "alert")
        myAlert.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
        myAlert.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
        self.present(myAlert,completion: nil)
    }
}

AlertViewController.swift

import UIKit
class AlertViewController: UIViewController {

    @IBAction func dismissButtonTapped(_ sender: UIButton) {
        self.dismiss(animated: true,completion: nil)
    }
}

不要忘记连接插座.

您可以将onTouchUp事件侦听器添加到后台视图,以在用户单击其外部时关闭该弹出窗口.

而已.你应该能够做出任何你能想象到的警报.不需要第三方代码.

这是我做的另一个自定义警报.仍然很难看,但它显示了你可以做的更多事情.

enter image description here

其他选择

但有时候没有必要重新发明轮子.我对第三方项目SDCAlertView(麻省理工学院许可证)印象深刻.它是用Swift编写的,但您也可以将它与Objective-C项目一起使用.它提供广泛的可定制性.

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...