在 Swift 中创建自定义 UIView 并显示为弹出窗口

Posted

技术标签:

【中文标题】在 Swift 中创建自定义 UIView 并显示为弹出窗口【英文标题】:Creating Custom UIView and display as Pop Up in Swift 【发布时间】:2015-03-23 06:05:02 【问题描述】:

我正在尝试创建一个自定义 UIView 并使用 Swift 在我的主视图中将其显示为弹出窗口。

我的自定义UIView 代码是

class DatePopUpView: UIView 
var uiView:UIView?

override init()  
    super.init()
    self.uiView = NSBundle.mainBundle().loadNibNamed("DatePopUpView", owner: self, options: nil)[0] as? UIView



required init(coder aDecoder: NSCoder) 
    super.init(coder: aDecoder)
      

required override init(frame: CGRect) 
           super.init(frame: frame)




我在主视图中将其称为:

 @IBAction func date_button_pressed (sender : AnyObject?) 
 var popUpView = DatePopUpView()
 var centre : CGPoint = CGPoint(x: self.view.center.x, y: self.view.center.y)

    popUpView.center = centre
    popUpView.layer.cornerRadius = 10.0
  let trans = CGAffineTransformScale(popUpView.transform, 0.01, 0.01)
    popUpView.transform = trans
    self.view .addSubview(popUpView)
    UIView .animateWithDuration(0.5, delay: 0.0, options:     UIViewAnimationOptions.CurveEaseInOut, animations: 

        popUpView.transform = CGAffineTransformScale(popUpView.transform, 100.0, 100.0)

        , completion: 
            (value: Bool) in

    )

 

但是 popUp 不会出现。我使用了断点并注意到值被分配给我的 popUpView 但它仍然没有显示在我的主视图上。请帮忙

请注意:我将 StoryBoard 用于我的 mainView 和我使用 xib 制作的自定义视图。

【问题讨论】:

你确定你的 date_button_pressed() 函数被调用了吗? 让我们continue this discussion in chat。 好的,现在我怀疑你的观点了。 你为什么不临时创建一个单独的项目。在主 vc 中加载你的 nib,看看你是否可以看到和调整你的视图。如果它看起来不错,那么我们可以重新审视这种情况 我尝试提供框架并添加 var popUpView = DatePopUpView() popUpView.frame = CGRectMake(40, 40, 200, 200) self.view .addSubview(popUpView) 但没有成功 【参考方案1】:

尝试将您的视图修改为以下内容:

class DatePopUpView: UIView 
     var uiView:UIView?
     override init()  
         super.init()
         self.setup()
     
     required init(coder aDecoder: NSCoder)  
         super.init(coder: aDecoder)
         self.setup()
     
     override init(frame: CGRect)   
         super.init(frame: frame)
         self.setup()
     
     setup() 
         self.uiView = NSBundle.mainBundle().loadNibNamed("DatePopUpView", owner: self, options: nil)[0] as? UIView
         self.uiView.frame = self.bounds
         self.uiView.autoresizingMask = .FlexibleWidth | .FlexibleHeight
         self.addSubview(self.uiView)
     

【讨论】:

【参考方案2】:

在故事板中

在storyboard中创建一个UIViewController 将自定义类设置为 anotherViewController 并将 Storyboard_ID 设置为 another_view_sid 创建一个新的 Cocoa Touch 类作为 anotherViewController 和 UIVIewController 的子类

在视图控制器中

    let popvc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "another_view_sid") as! anotherViewController

    self.addChildViewController(popvc)

    popvc.view.frame = self.view.frame

    self.view.addSubview(popvc.view)

    popvc.didMove(toParentViewController: self)

在另一个视图控制器中

override func viewDidLoad() 
    super.viewDidLoad()
        showAnimate()
    


@IBAction func Close_popupView(_ sender: Any) 
    removeAnimate()


func showAnimate()

    self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
    self.view.alpha = 0.0
    UIView.animate(withDuration: 0.25, animations: 
        self.view.alpha = 1.0
        self.view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
    )


func removeAnimate()

    UIView.animate(withDuration: 0.25, animations: 
        self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
        self.view.alpha = 0.0
    , completion: (finished : Bool) in
        if(finished)
        
            self.willMove(toParentViewController: nil)
            self.view.removeFromSuperview()
            self.removeFromParentViewController()
        
    )

【讨论】:

这是动画代码,效果很好。但是,如何显示为像 alertview 这样的弹出窗口?【参考方案3】:

将视图呈现为模态转场

查看本教程:

http://makeapppie.com/2014/08/30/the-swift-swift-tutorials-adding-modal-views-and-popovers/

您可以使用系统提供的转场转场或进行自定义转场转场以获得真正精美的效果。

这是制作自定义过渡动画师的一种方法:

//
//  BaseTransitionAnimator.swift
//

import UIKit

class BaseTransitionAnimator : NSObject, UIViewControllerAnimatedTransitioning 

    enum PresentationMode 
        case Presenting, Dismissing
    
    var duration     : NSTimeInterval = 1.0
    var mode         : PresentationMode = .Presenting

    init(duration: NSTimeInterval, mode: PresentationMode) 
        self.duration = duration
        self.mode = mode
    

    func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval 
        return duration
    

    func animateTransition(transitionContext: UIViewControllerContextTransitioning) 
        // stub - must be overriden by inheritor
    

//
//  ExpandingTransitionAnimator.swift
//

import UIKit

class ExpandingTransitionAnimator : BaseTransitionAnimator 

    enum ExpansionMode 
        case Basic, WithFadingImage
    

    var image : UIImage? = nil

    override init(duration: NSTimeInterval, mode: PresentationMode) 
        super.init(duration: duration, mode: mode)
    

    override func animateTransition(transitionContext: UIViewControllerContextTransitioning) 
        var fromVC             = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!
        var toVC               = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!
        var fromView           = fromVC.view
        var toView             = toVC.view
        var containerView      = transitionContext.containerView()
        var duration           = transitionDuration(transitionContext)
        var initialFrame       = transitionContext.initialFrameForViewController(fromVC)

        var imageView : UIImageView?
        if image != nil 
            imageView = UIImageView(image: image!.crop(CGPointMake(0, 0),  size: toView.frame.size))

        
        if (mode == .Presenting)   
                toView.transform = CGAffineTransformMakeScale(0.05, 0.05)
               var originalCenter = toView.center
                containerView.addSubview(toView)
                if imageView != nil 
                    imageView!.transform = CGAffineTransformMakeScale(0.05, 0.05);
                    containerView.addSubview(imageView!)
                

                UIView.animateWithDuration(duration,
                    delay:0.0,
                    options:.CurveEaseInOut,
                    animations: 
                        if imageView != nil 
                            imageView!.alpha = 0.0
                            imageView!.transform =  CGAffineTransformMakeScale(1.0, 1.0)
                        
                        toView.transform =  CGAffineTransformMakeScale(1.0, 1.0)
                        toView.center = originalCenter
                    ,
                    completion:  _ in
                        transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
                )
         else  // dismissing
            UIView.animateWithDuration(duration,
                animations: 
                    fromView.transform = CGAffineTransformMakeScale(0.05, 0.05)
                    fromView.center = toView.center
                ,
                completion:  _ in
                    fromView.removeFromSuperview()
                    transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
            )
        
    

【讨论】:

这意味着我应该创建一个 UIViewcontroller 并使用 suegue 以模态方式呈现它,而不是 UIView? 该代码仅适用于 iPad。其中提到。我正在使用 iPhone 让我们continue this discussion in chat。【参考方案4】:

在 DatePopUpView 中,您似乎正在加载 nib 文件,但实际上并未将其作为子视图添加到视图中。

【讨论】:

【参考方案5】:

Mili Shah 回答的 Swift 5 版本

let popvc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "another_view_sid") as! anotherViewController

self.addChild(popvc)
popvc.view.frame = self.view.frame
self.view.addSubview(popvc.view)
popvc.didMove(toParent: self)

@IBAction func Close_popupView(_ sender: Any) 
    removeAnimate()


func showAnimate() 
    self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
    self.view.alpha = 0.0
    UIView.animate(withDuration: 0.25, animations: 
        self.view.alpha = 1.0
        self.view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
    )


func removeAnimate() 
    UIView.animate(withDuration: 0.25, animations: 
        self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
        self.view.alpha = 0.0
    , completion: (finished : Bool) in
        if(finished)
        
            self.willMove(toParent: nil)
            self.view.removeFromSuperview()
            self.removeFromParent()
        
    )

【讨论】:

以上是关于在 Swift 中创建自定义 UIView 并显示为弹出窗口的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Xcode 中创建自定义 UIView?

重构大方法以在 UIViewController 中创建自定义 UIView

swift 在Swift中创建自定义运算符

如何在 Swift Combine 中创建自定义链?

如何在 Swift Xcode 中创建自定义导航栏?

在 Swift 中创建自定义(八角形)UIButton 的最佳方法