簡體   English   中英

從.xib實例化將UI手勢識別器添加到UIView

[英]Add UI Gesture Recognizer to UIView instantiated from .xib

我正在使用Xcode 10.0 beta 4和Swift 4,我想為左右滑動向UIView添加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 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,並將視圖的類設置為Calendar類,並且在.xib中的此類標簽在我將任何手勢識別器添加到calendar(View)或日歷中的對象無法識別手勢。 這是做這樣事情的正確方法還是我應該采取一種完全不同的方法?

編輯:我已經包括了我的IB .xib和.storyboard的外觀,如果有幫助的話。 故事板XIB

為了能夠在我的.xib中使用手勢識別器,我在自定義UIView Calendar類中使用了awakeFromNib()的重寫:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM