2017-11-08 12 views
0

私は、ストーリーボードから1つのMainViewControllerとxibから1つのModalUIViewを持っています。Swift4 ViewControllerサブビュー内でイベントを発生させない

In ModalUIViewには、モーダルを閉じるためのモーダルとディスマイス関数を表示する関数があります。

ステップ: MainViewController - > OpenModal - > ModalUIView - >ここで

は私のコードですCloseModal:

UIViewUtil.swift

import Foundation 
import UIKit 

extension UIView { 
    // Load xib as the same name of CustomView that want to use xib 
    func loadXib() -> UIView{ 
     let bundle = Bundle(for: type(of: self)) 
     let nibName = type(of: self).description().components(separatedBy: ".").last! 
     let nib = UINib(nibName: nibName, bundle: bundle) 
     return nib.instantiate(withOwner: self, options: nil).first as! UIView 
    } 
} 

MainViewController.swift

のUIViewControllerのサブクラスであります
@IBAction func guideButton(_ sender: Any) { 
    let modal = ModalUIView() 
    modal.present(targetView: self.view) 
} 

ModalUIVi ew.swiftは、私がmodalUIViewの存在と呼ばれ、その後、私はmodalUIViewでcloseButton上のタブは私が@IBActionと試みるが、それは動作しないアクション

を発射していないときに私の問題がmainViewControllerあるのUIView

var view : UIView? 

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

    setup() 
} 

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

    setup() 
} 

func setup() { 
    view = loadXib() 
} 

func present(targetView: UIView) { 
    view!.layer.cornerRadius = 10.0 
    view!.clipsToBounds = true 

    targetView.addSubview(view!) 

    // Set size 
    let popupWidth: CGFloat = targetView.frame.width - (targetView.frame.width * 0.04) 
    let popupHeight: CGFloat = targetView.frame.height - (targetView.frame.height * 0.08) 

    view!.frame = CGRect(x: targetView.frame.origin.x, y: targetView.frame.origin.y, 
         width: popupWidth, height: popupHeight) 

    view!.center = targetView.center 

    view!.transform = CGAffineTransform.init(scaleX: 1.3, y: 1.3) 
    view!.alpha = 0 

    UIView.animate(withDuration: 0.4){ 
     self.view!.alpha = 1 
     self.view!.transform = CGAffineTransform.identity 
    } 
} 

@objc func dismiss(sender: UIButton!) { 
    print("dismiss") 
} 

のサブクラスであります:

@IBAction func CloseButtonAction(_ sender: UIButton) { 
} 

私はまた、プログラムによる手動追加アクションを試みるが、それはあまりにも動作しません:

let closeButton: UIButton? = view?.viewWithTag(10) as! UIButton 
closeButton!.addTarget(self, action: #selector(dismiss), for: .touchUpInside) 

注:私はモーダルでcloseButtonを見てタップできます。 xibファイルの所有者に既にModalUIViewを追加しています

答えて

0

OK、解決策がありますが、それが最善の答えです。

私のソリューションは、誰もがこれよりも別の最適なソリューションを持っている場合は、私を提案してくださいませんmodalUIView

にmainViewController経由modalUIViewのcloseButtonにアクションを追加することです。

0

以下のように、あなたのビューコントローラでアクションを取得することもできます。

yourSubView.button.addTarget(self, action: #selector(buttonPress(sender:)), for: .touchUpInside) 

あなたのメソッドが呼び出されます。

func buttonPress(sender:UIButton){ 
print("Button pressed") 
} 
関連する問題