Swift4 ViewController没有在subView中触发事件

时间:2017-11-08 08:17:32

标签: ios swift uiview uiviewcontroller subview

我有来自故事板的1个MainViewController和来自xib的1个ModalUIView。

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

ModalUIView.swift是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")
}

当我调用modalUIView的present时,我的问题是mainViewController然后我在modalUIView中的closeButton上的tab没有触发动作

我尝试使用@IBAction,但它不起作用:

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

我也尝试通过编程方式手动添加操作,但它也不起作用:

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

注意: 我可以在模态上看到并点击closeButton。 我已经将ModalUIView添加到xib文件的所有者

2 个答案:

答案 0 :(得分:0)

好的,我现在有一个解决方案,但不确定这是最好的答案。

我的解决方案是通过mainViewController向modalUIView的closeButton添加一个动作而不是modalUIView

如果有人有另一个最佳解决方案,请建议我。

答案 1 :(得分:0)

您还可以在viewcontroller中获取操作。

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

它会调用你的方法。

func buttonPress(sender:UIButton){
print("Button pressed")
}