自定义警报(UIAlertView)与迅速
我怎样才能创build一个自定义警报与斯威夫特? 我尝试翻译从目标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)
在animation中它是透明的,但当animation结束时,它是不透明的…我closures了视图中的不透明选项…我做错了什么?
代码在Swift 4和Xcode 9中testing过
如何制作自己的自定义警报
我想要做类似的事情。 首先, UIAlertView
不赞成使用UIAlertController
。 看到这个答案的标准方式来显示一个警报:
- 我将如何在Swift中创build一个UIAlertView?
而且UIAlertView
和UIAlertController
都没有真正允许很多定制。 一种select是使用一些第三方代码。 但是,我发现通过模态地显示另一个视图控制器来创build自己的警报并不困难。
这里的例子只是一个概念validation。 你可以任何你想要的方式devise你的警报。
故事板
你应该有两个视图控制器。 你的第二个视图控制器将是你的警报。 将类名称设置为AlertViewContoller
和Storyboard ID以alert
。 (这两个都是我们在下面的代码中定义的名字,没有什么特别的,如果你愿意,可以先添加代码,如果你先添加代码,实际上可能会更容易。
设置根视图的背景颜色(在警报视图控制器中)清除。 添加另一个UIView
并将其与约束中心。 用它作为你的警戒背景,并把你想要的东西放在里面。 对于我的例子,我添加了一个UIButton
。
码
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, animated: true, completion: nil) } }
AlertViewController.swift
import UIKit class AlertViewController: UIViewController { @IBAction func dismissButtonTapped(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } }
不要忘记连接网点。
而已。 你应该能够做出任何你现在可以想象的警报。 不需要第三方代码。
其他选项
不过,有时候不需要重新发明轮子。 我对第三方项目SDCAlertView (MIT许可证)印象深刻。 它是用Swift编写的,但是也可以在Objective-C项目中使用它。 它提供了广泛的可定制性。
这是Swift 3代码。 非常感谢@Suragch创造一个自定义AlertView真棒的方法。
ViewController.swift
import UIKit class ViewController: UIViewController { @IBAction func showAlertButtonTapped(sender: UIButton) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let myAlert = storyboard.instantiateViewController(withIdentifier: "storyboardID") myAlert.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext myAlert.modalTransitionStyle = UIModalTransitionStyle.crossDissolve self.present(myAlert, animated: true, completion: nil) }
AlertViewController.swift
import UIKit class AlertViewController: UIViewController { @IBAction func dismissButtonTapped(sender: UIButton) { self.dismiss(animated: true, completion: nil) } }
为了让它更有趣一些,或者在iOS中设置默认效果,你可以添加一个VisualEffectView,或者将主UIView的颜色改成深色,并将其alpha设置为70%。 我更喜欢第二种方法,因为模糊效果并不像使用70 alpha的视图那样平滑。
效果与VisualEffectView:
使用70 Alpha的UIView的效果: