我的目标是显示一个 Collection View 单元格,如果您点击它,它将打开一个新的 View Controller (MovieDetailA)。或者,如果您长按,则会打开一个弹出菜单 (MovieDetailB)。
我的项目设置方式是使用 XIBS。我的 Collection View 分解如下:
- MovieCollectionViewCell.swift - (cell)
- MovieCollectionViewController - (cell's functionality)
- MovieMain.swift - (displays collection view).
当用户点击单元格时, Collection View 正在工作,MovieDetailA 正在工作。我使用 NSNotifications
和 NotificationCenter.default.addObserver
进行操作。
我的问题是我不知道如何将通知应用到 UILongPressGesture
。我已经发布了 MovieMain.swift 的代码并对其进行了编辑以仅关注上述问题。
override func viewDidLoad() {
super.viewDidLoad()
let gesture = UILongPressGestureRecognizer(target:self,
action:#selector(movieSelected(notification:)))
gesture.minimumPressDuration = 0.5
gesture.delaysTouchesBegan = true
collectionView.addGestureRecognizer(gesture)
}
override func addObservers() {
super.addObservers()
NotificationCenter.default.addObserver(self, selector: #selector(movieSelected(notification:)), name:
NOTIF_MOVIE_SELECTED, object: nil) }
@objc func movieSelected(notification: NSNotification) {
guard let movie = notification.object as? Movie else { -- I think error is coming from this line.
return
} }
运行应用程序后,我收到以下错误,
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UILongPressGestureRecognizer object]: unrecognized selector sent to instance
最佳答案
问题是您使用方法movieSelected(notification:)
作为长按的操作
let gesture = UILongPressGestureRecognizer(target:self,
action:#selector(movieSelected(notification:)))
在这一行
guard let movie = notification.object
您向 UILongPressGestureRecognizer
类型的通知
询问肯定不存在的object
属性,因此崩溃
该方法适用于此通知
NotificationCenter.default.addObserver(self, selector: #selector(movieSelected(notification:)), name:
要实现您的目标,您必须将长按添加到 awakeFromNib
中的单元格
并在此方法中发布通知
@objc func movieSelected(notification: NSNotification) {
NotificationCenter.default.post(name: Notification.Name(NOTIF_MOVIE_SELECTED), object:self)
}
根据包含 collectionView 的 VC 中的观察者,您将获得单元格本身并询问其当前模型以在弹出窗口中显示
关于ios - 带有 CollectionViewCell 和 UILongPressGesture 错误的 XIB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49204481/