2016-06-15 1 views
0

Я пытаюсь показать некоторый контент с пользовательским UIView как всплывающее окно, до сих пор я сделал это хорошо, я хочу выпустить всплывающее окно, коснувшись всплывающего окна, я не могу добиться успеха, я новичок в быстром языке, пожалуйста, вы можете мне помочь с этим, все только код, скопированный из Google толькоНеполадки при нажатии и отсутствии событий, которые создаются с помощью пользовательского uiview с xib?

код для Пользовательской UIView

import UIKit 

class PopUpView: UIView { 
    var view = UIView() 
    var _myTap: UITapGestureRecognizer? 
    // this name has to match your class file and your xib file 
    @IBOutlet weak var lblContent: UILabel! 

    override init(frame: CGRect) { 
     super.init(frame: frame) 
     setup() 
    } 
    required init?(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
     setup() 
    } 
    override func awakeFromNib() 
    { 
     self.userInteractionEnabled = true 
    } 
    func _myHandleTap(sender: UITapGestureRecognizer) { 
     if sender.state == .Ended { 
      print("_myHandleTap(sender.state == .Ended)") 
      sender.view!.backgroundColor 
       = UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1.0); 
      self .hideInView() 
     } 
    } 
    func setup() { 
     // setup the view from .xib 
     view = loadViewFromNib() 
     view .userInteractionEnabled = true 
     self .userInteractionEnabled = true 
     view.backgroundColor = UIColor.clearColor() 
     _myTap = UITapGestureRecognizer(target: self 
      , action: #selector(_myHandleTap(_:))) 
     _myTap!.numberOfTapsRequired = 1 
     view.addGestureRecognizer(_myTap!) 

    } 

    func loadViewFromNib() -> UIView { 
     // grabs the appropriate bundle 
     let bundle = NSBundle(forClass: self.dynamicType) 
     let nib = UINib(nibName: "PopUpView", bundle: bundle) 
     let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView 
     return view 
    } 
    func showInView(currentView:UIView,content:String) { 
     view.frame = currentView.bounds 
     currentView .userInteractionEnabled = true 
     lblContent.text = content 
     UIApplication.sharedApplication().keyWindow!.addSubview(view) 
     view.alpha = 0 
     UIView.animateWithDuration(0.2, delay: 0.2, options: [.CurveEaseInOut], animations: { 
      self.view.alpha = 1 
      }, completion: nil) 

    } 
    func hideInView() { 
     view.alpha = 0 
     UIView.animateWithDuration(0.2, delay: 0.2, options: [.Repeat, .CurveEaseInOut], animations: { 
      self.view.alpha = 0 
      self.view .removeFromSuperview() 
      }, completion: nil) 

    } 
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 
     self .hideInView() 
    } 
    func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { 

     return true 

    } 
} 

к нему доступ из моего UIViewController

@IBAction func doForgotAction(sender: AnyObject) { 
//  warning: could not load any Objective-C class information. This will significantly reduce the quality of type information available. 
     let custom = PopUpView() 
     custom .showInView(self .view, content: "welcome") 

    } 
+0

Ваша функция _myHandleTap называется? –

+0

, который не звонит, я проверил с точкой останова. –

ответ

1

Наконец я получил мой ответ, Основная проблема заключается в события не получили, созданы ли его по XIB или программно

Я изменил весь код ниже

import UIKit 

class PopUpView: UIView { 
    var view = UIView() 
    // this name has to match your class file and your xib file 
    @IBOutlet weak var containerView: UIView! 
    @IBOutlet weak var lblContent: UILabel! 
    @IBOutlet weak var _myTap: UITapGestureRecognizer! 
    override init(frame: CGRect) { 
     super.init(frame: frame) 
     setup() 
    } 
    required init?(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
     setup() 
    } 
    override func awakeFromNib() 
    { 
     super.awakeFromNib() 
    } 
    @IBAction func tapGestureAction(sender: AnyObject) { 
     self .hideInView() 
    } 
    func setup() { 
     // setup the view from .xib 
     view = loadViewFromNib() 
     view.frame = bounds 
     self .userInteractionEnabled = true 
     view.backgroundColor = UIColor.greenColor() 
     view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight] 
     addSubview(view) 
    } 

    func loadViewFromNib() -> UIView { 
     // grabs the appropriate bundle 
     let bundle = NSBundle(forClass: self.dynamicType) 
     let nib = UINib(nibName: "PopUpView", bundle: bundle) 
     let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView 
     return view 
    } 
    func showInView(currentView:UIView,content:String) { 
     self.frame = currentView.bounds 
     self .layoutIfNeeded() 
     lblContent.text = content 
     UIApplication.sharedApplication().keyWindow!.addSubview(self) 
     self.alpha = 0 
     UIView.animateWithDuration(0.2, delay: 0.2, options: [.CurveEaseInOut], animations: { 
      self.alpha = 1 
      }, completion: nil) 

    } 
    func hideInView() { 
     self.alpha = 1 
     UIView.animateWithDuration(0.2, delay: 0.2, options: [.Repeat, .CurveEaseInOut], animations: { 
      self.alpha = 0 
      self .removeFromSuperview() 
      }, completion: nil) 

    } 

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 
     self .hideInView() 
    } 
    func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { 

     return true 

    } 
} 

Все работает хорошо после изменение этой последующей линии

func setup() { 
     // setup the view from .xib 
     view = loadViewFromNib() 
     view.frame = bounds 
     self .userInteractionEnabled = true 
     view.backgroundColor = UIColor.greenColor() 
     view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight] 
     addSubview(view) 

}

Теперь я могу получить tapgesture и touchevents.

0

Вы должны создать метод действия выхода в своем классе пользовательского вида, а также жестом касания и нажатия в этом классе. Теперь, чтобы получить эффект этих касаний и кранов, вам необходимо создать делегат и добавить метод делегата к вашему контроллеру вида, чтобы получать штрихи и нажатия.

+0

Почему его не работает программно? –

 Смежные вопросы

  • Нет связанных вопросов^_^