【发布时间】:2017-02-06 21:26:44
【问题描述】:
我的视图控制器上有一个按钮,它带来了一个菜单和一个稍微透明的视图 blackView 在它后面 - 菜单类包括一个点击手势识别器,用于在点击 blackView 时关闭菜单。但是它没有响应,我不确定我的问题出在哪里。这是菜单的代码:
class MenuController: NSObject, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
let blackView = UIView()
let collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = UIColor.white
return cv
}()
let cellId = "cellId"
func presentMenu() {
if let window = UIApplication.shared.keyWindow {
blackView.backgroundColor = UIColor(white: 0, alpha: 0.5)
blackView.isUserInteractionEnabled = true
// Tap outside to dismiss
blackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleDismiss)))
window.addSubview(blackView)
window.addSubview(collectionView)
let height: CGFloat = 200
let y = window.frame.height - height
collectionView.frame = CGRect(x: 0, y: window.frame.height, width: window.frame.width, height: height)
blackView.frame = window.frame
blackView.alpha = 0
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
self.blackView.alpha = 1
self.collectionView.frame = CGRect(x: 0, y: y, width: self.collectionView.frame.width, height: self.collectionView.frame.height)
}, completion: nil)
}
}
func handleDismiss() {
print("working")
UIView.animate(withDuration: 0.5) {
self.blackView.alpha = 0
if let window = UIApplication.shared.keyWindow {
self.collectionView.frame = CGRect(x: 0, y: window.frame.height, width: self.collectionView.frame.width, height: self.collectionView.frame.height)
}
}
}
// Collection view data sources
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
return cell
}
override init() {
super.init()
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(MenuCell.self, forCellWithReuseIdentifier: cellId)
}
}
presentMenu 被调用,当我点击视图控制器上的必要按钮时菜单出现。但是handleDismiss 没有被调用。感谢您的帮助,希望这只是一个初学者的错误!
解决方案后编辑:我在视图控制器中初始化 menuController(),如下所示:
func showMenu() {
let menuController = MenuController()
menuController.presentMenu()
}
并将其更改为@ronatory 的解决方案
lazy var menuController: MenuController = {
let menuController = MenuController()
return menuController
}()
func showMenu() {
menuController.presentMenu()
}
解决了。
【问题讨论】:
-
有什么原因需要每次使用菜单的框架都要换吗?
-
我只是认为从逻辑上讲,早点初始化菜单是有意义的,只需将
animate代码保留在present()和dismiss()函数中 -
你能告诉剩下的课程吗?尤其是您如何创建
collectionView? -
而且,如果我正确理解您的逻辑,您是在分别呈现菜单和视图以实现菜单视图外观吗?这不是解决这个问题的好方法。将集合视图添加到您正在呈现的视图中会更有意义。
-
你能在 GitHub 上分享你的项目吗?如果您需要,这将使您更容易为您提供帮助
标签: ios swift swift3 uitapgesturerecognizer