将 UI 手势识别器添加到 UI 从 .xib 实例化的视图

Add UI Gesture Recognizer to UIView instantiated from .xib

我正在使用 Xcode 10.0 beta 4 和 Swift 4,我正在尝试添加一个 UIGestureRecognizers,特别是一个 UISwipeGestureRecognizer,用于左右滑动到已添加的 UIView通过笔尖作为我的主视图控制器的子视图,但不幸的是,当我在模拟器中实际执行操作时,手势似乎无法识别。这是我的 viewDidLoad() 中的一个片段:

    //Add gesture recognizer for when the calendar is swiped right.
    let grSwipeRight = UISwipeGestureRecognizer(target: self, action: #selector(swipeRight(sender:)))
    grSwipeRight.direction = UISwipeGestureRecognizer.Direction.right
    calendar.calendarDays.isUserInteractionEnabled = true
    calendar.calendarDays.addGestureRecognizer(grSwipeRight)

选择器中的 swipeRight 操作是针对仅包含 print() 调用的函数,日历是对我的 UIView 的引用,它是我的 .xib

中使用的 class
class Calendar: UIView
{
@IBOutlet var calendarDays: UICollectionView!
let nibName = "Calendar"
var contentView: UIView?

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

    guard let view = self.loadViewFromNib() else { return }
    view.frame = self.bounds
    self.addSubview(view)
    self.bringSubviewToFront(view)
    contentView = view
    contentView?.isUserInteractionEnabled = true
}

private func loadViewFromNib() -> UIView? {
    let bundle = Bundle(for: type(of: self))
    let nib = UINib(nibName: nibName, bundle: bundle)
    return nib.instantiate(withOwner: self, options: nil).first as? UIView
}

我使用 Interface Builder 将 .xib 设置为 UIView,并将视图的 class 设置为我的日历 class 并且我的 .xib 中的标签等正确显示我将任何手势识别器添加到日历(视图)或日历中的对象,但无法识别手势。这甚至是做这样的事情的正确方法还是我应该采取完全不同的方法?

编辑: 我已经包括了我的 IB .xib 和 .storyboard 的样子,如果它有帮助的话。 Storyboard, xib

为了能够在我的 .xib 中使用手势识别器,我在我的自定义 UIView 日历中使用了 awakeFromNib() 的覆盖,如下所示 class:

 override func awakeFromNib()
{
    super.awakeFromNib()
    let touchTest = UITapGestureRecognizer(target: self, action: #selector(self.testTap(sender:)))
    testingLabel.isUserInteractionEnabled = true
    testingLabel.addGestureRecognizer(touchTest)
}