如何使用 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
。有关显示警报的标准方式,请参阅此答案:
UIAlertView
和 UIAlertController
都不允许太多定制。一种选择是使用一些第三方代码。但是,我发现通过模态显示另一个视图控制器来创建自己的警报并不难。
这里的例子只是一个概念验证。您可以按照自己的方式设计警报。
你应该有两个视图控制器。您的第二个视图控制器将是您的警报。将班级名称设置为
AlertViewContoller
,将情节提要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)
}
}
别忘了连接插座。
您可以将
onTouchUp
事件侦听器添加到背景视图,以在用户单击它的外部时关闭弹出窗口。
就是这样。您应该能够发出您现在可以想象的任何类型的警报。无需第三方代码。
这是我制作的另一个自定义警报。仍然很丑陋,但它显示了您可以做的更多事情。
不过,有时不需要重新发明轮子。第三方项目 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 的效果:
如今,警报只是一个简单的呈现视图控制器。您可以编写一个呈现的视图控制器,它的行为类似于警报——也就是说,它会弹出到屏幕上并使它后面的任何东西变暗——但它是your 视图控制器,您可以自由地给它任何你喜欢的界面。
为了让你开始,我写了一个github项目,你可以下载并运行,并根据你的实际需要进行修改。
我将展示代码的关键部分。 “警报”视图控制器在其初始化程序中将其自己的模态呈现样式设置为
custom
并设置一个转换委托:
class CustomAlertViewController : UIViewController {
let transitioner = CAVTransitioner()
override init(nibName: String?, bundle: Bundle?) {
super.init(nibName: nibName, bundle: bundle)
self.modalPresentationStyle = .custom
self.transitioningDelegate = self.transitioner
}
convenience init() {
self.init(nibName:nil, bundle:nil)
}
required init?(coder: NSCoder) {
fatalError("NSCoding not supported")
}
}
所有工作都由过渡代表完成:
class CAVTransitioner : NSObject, UIViewControllerTransitioningDelegate {
func presentationController(
forPresented presented: UIViewController,
presenting: UIViewController?,
source: UIViewController)
-> UIPresentationController? {
return MyPresentationController(
presentedViewController: presented, presenting: presenting)
}
}
class MyPresentationController : UIPresentationController {
func decorateView(_ v:UIView) {
// iOS 8 doesn't have this
// v.layer.borderColor = UIColor.blue.cgColor
// v.layer.borderWidth = 2
v.layer.cornerRadius = 8
let m1 = UIInterpolatingMotionEffect(
keyPath:"center.x", type:.tiltAlongHorizontalAxis)
m1.maximumRelativeValue = 10.0
m1.minimumRelativeValue = -10.0
let m2 = UIInterpolatingMotionEffect(
keyPath:"center.y", type:.tiltAlongVerticalAxis)
m2.maximumRelativeValue = 10.0
m2.minimumRelativeValue = -10.0
let g = UIMotionEffectGroup()
g.motionEffects = [m1,m2]
v.addMotionEffect(g)
}
override func presentationTransitionWillBegin() {
self.decorateView(self.presentedView!)
let vc = self.presentingViewController
let v = vc.view!
let con = self.containerView!
let shadow = UIView(frame:con.bounds)
shadow.backgroundColor = UIColor(white:0, alpha:0.4)
shadow.alpha = 0
con.insertSubview(shadow, at: 0)
shadow.autoresizingMask = [.flexibleWidth, .flexibleHeight]
let tc = vc.transitionCoordinator!
tc.animate(alongsideTransition: { _ in
shadow.alpha = 1
}) { _ in
v.tintAdjustmentMode = .dimmed
}
}
override func dismissalTransitionWillBegin() {
let vc = self.presentingViewController
let v = vc.view!
let con = self.containerView!
let shadow = con.subviews[0]
let tc = vc.transitionCoordinator!
tc.animate(alongsideTransition: { _ in
shadow.alpha = 0
}) { _ in
v.tintAdjustmentMode = .automatic
}
}
override var frameOfPresentedViewInContainerView : CGRect {
// we want to center the presented view at its "native" size
// I can think of a lot of ways to do this,
// but here we just assume that it *is* its native size
let v = self.presentedView!
let con = self.containerView!
v.center = CGPoint(x: con.bounds.midX, y: con.bounds.midY)
return v.frame.integral
}
override func containerViewWillLayoutSubviews() {
// deal with future rotation
// again, I can think of more than one approach
let v = self.presentedView!
v.autoresizingMask = [
.flexibleTopMargin, .flexibleBottomMargin,
.flexibleLeftMargin, .flexibleRightMargin
]
v.translatesAutoresizingMaskIntoConstraints = true
}
}
extension CAVTransitioner { // UIViewControllerTransitioningDelegate
func animationController(
forPresented presented:UIViewController,
presenting: UIViewController,
source: UIViewController)
-> UIViewControllerAnimatedTransitioning? {
return self
}
func animationController(
forDismissed dismissed: UIViewController)
-> UIViewControllerAnimatedTransitioning? {
return self
}
}
extension CAVTransitioner : UIViewControllerAnimatedTransitioning {
func transitionDuration(
using transitionContext: UIViewControllerContextTransitioning?)
-> TimeInterval {
return 0.25
}
func animateTransition(
using transitionContext: UIViewControllerContextTransitioning) {
let con = transitionContext.containerView
let v1 = transitionContext.view(forKey: .from)
let v2 = transitionContext.view(forKey: .to)
// we are using the same object (self) as animation controller
// for both presentation and dismissal
// so we have to distinguish the two cases
if let v2 = v2 { // presenting
con.addSubview(v2)
let scale = CGAffineTransform(scaleX: 1.6, y: 1.6)
v2.transform = scale
v2.alpha = 0
UIView.animate(withDuration: 0.25, animations: {
v2.alpha = 1
v2.transform = .identity
}) { _ in
transitionContext.completeTransition(true)
}
} else if let v1 = v1 { // dismissing
UIView.animate(withDuration: 0.25, animations: {
v1.alpha = 0
}) { _ in
transitionContext.completeTransition(true)
}
}
}
}
它看起来像很多代码,我想是的,但它几乎完全局限于一个类,完全是样板;只需复制和粘贴。 您所要做的就是编写“警报”视图控制器的内部界面和行为,为其提供按钮和文本以及您想要的任何其他内容,就像您为任何其他视图控制器所做的那样。
import UIKit
class Dialouge: UIView {
@IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var lblDescription: UILabel!
@IBOutlet weak var btnLeft: UIButton!
@IBOutlet weak var btnRight: UIButton!
@IBOutlet weak var viewBg: UIButton!
var leftAction = {}
var rightAction = {}
override func draw(_ rect: CGRect)
{
self.btnRight.layer.cornerRadius = self.btnRight.frame.height/2
self.btnLeft.layer.cornerRadius = self.btnLeft.frame.height/2
self.btnLeft.layer.borderWidth = 1.0
self.btnLeft.layer.borderColor = #colorLiteral(red: 0.267678082, green: 0.2990377247, blue: 0.7881471515, alpha: 1)
}
@IBAction func leftAction(_ sender: Any) {
leftAction()
}
@IBAction func rightAction(_ sender: Any) {
rightAction()
}
@IBAction func bgTapped(_ sender: Any) {
self.removeFromSuperview()
}
}
强文
## 使用 Tabbar 自定义警报.
let custView = Bundle.main.loadNibNamed("Dialouge", owner: self, options:
nil)![0] as? Dialouge
custView?.lblDescription.text = "Are you sure you want to delete post?"
custView?.lblTitle.text = "Delete Post"
custView?.btnLeft.setTitle("Yes", for: .normal)
custView?.btnRight.setTitle("No", for: .normal)
custView?.leftAction = {
self.deletePost(postId: self.curr_post.id,completion: {
custView?.removeFromSuperview()
})
}
custView?.rightAction = {
custView?.removeFromSuperview()
}
if let tbc = self.parentt?.tabBarController {
custView?.frame = tbc.view.frame
DispatchQueue.main.async {
tbc.view.addSubview(custView!)
}
}else if let tbc = self.parView?.parenttprof {
custView?.frame = tbc.view.frame
DispatchQueue.main.async {
tbc.view.addSubview(custView!)
}
}
else
{
custView?.frame = self.parView?.view.frame ?? CGRect.zero
DispatchQueue.main.async {
self.parView?.view.addSubview(custView!)
}
}
使用https://github.com/shantaramk/Custom-Alert-View
实现起来毫不费力。请按照以下步骤操作:
在工程目录下拖拽AlertView文件夹
显示警报视图弹出窗口
func showUpdateProfilePopup(_ message: String) {
let alertView = AlertView(title: AlertMessage.success, message: message, okButtonText: LocalizedStrings.okay, cancelButtonText: "") { (_, button) in
if button == .other {
self.navigationController?.popViewController(animated: true)
}
}
alertView.show(animated: true)
}