自定义警报(UIAlertView)与swift

时间:2014-08-19 09:08:49

标签: 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)

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

5 个答案:

答案 0 :(得分:27)

在Swift 4和Xcode 9中测试的代码

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

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

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

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

enter image description here

故事板

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

enter image description here

设置根视图的背景颜色(在警报视图控制器中)以清除。添加另一个UIButton并以约束为中心。使用它作为你的警报背景,并把你想要的东西放在里面。在我的例子中,我添加了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) } }

enter image description here

代码

ViewController.swift

import UIKit
class AlertViewController: UIViewController {

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

AlertViewController.swift

.tdata.ng-scope {
  float: left;
}

不要忘记连接插座。

就是这样。你应该能够做出任何你能想象到的警报。不需要第三方代码。

其他选项

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

答案 1 :(得分:15)

这是 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的效果:

enter image description here

使用带有70 Alpha的UIView的效果:

enter image description here

答案 2 :(得分:1)

使用https://github.com/shantaramk/Custom-Alert-View

轻松实现此目标。只需执行以下步骤:

  1. 下拉项目目录中的AlertView文件夹

  2. 显示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)
    

    }

答案 3 :(得分:1)

如今,警报只是一个简单的呈现视图控制器。您可以编写一个呈现的视图控制器,其行为类似于警报-即它弹出到屏幕上并使背后的任何内容变暗-但它是您的 视图控制器,您可以随意为其提供任何界面你喜欢。

为使您入门,我编写了github project,您可以下载并运行并进行修改以满足您的实际需求。

我将显示代码的关键部分。 “警报”视图控制器在其初始化程序中将其自身的模式表示样式设置为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)
            }
        }

    }
}

它看起来像很多代码,我想是的,但是几乎全部都局限于一个类,它完全是样板。只需复制并粘贴。 所要做的就是编写“警报”视图控制器的内部界面和行为,为它提供按钮和文本以及您想要的任何其他内容,就像您对其他任何视图控制器所做的一样。 / p>

答案 4 :(得分:1)

swift 4中的自定义警报UIView类和用法##

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

强文本
        ## 通过标签栏使用自定义提醒

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