我有1个来自Storyboard的MainViewController和1个来自xib的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上的选项卡未触发

我尝试使用@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文件的所有者

最佳答案

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

我的解决方案是通过mainViewController将操作添加到modalUIView的closeButton中,而不是modalUIView中

如果还有其他最佳解决方案,请提出建议。

关于ios - Swift4 ViewController未触发subView中的事件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47174641/

10-09 16:18