【发布时间】:2017-04-21 13:02:40
【问题描述】:
我正在通过 swift 做一个项目。我已经定义了一个集合视图并自定义了它的单元格,使它看起来像图像 down 。现在,一旦我点击单元格,我的函数将告诉我我点击了哪个单元格,但我想获得更详细的信息,例如我在单元格编号 2 中获得图片。为此,我试图定义一个轻击手势,但它似乎不起作用?这是我所有的代码:
导入 UIKit 导入 AVFoundation 导入 AVKit
class ViewUSRController: UIViewController , UICollectionViewDelegate , UICollectionViewDataSource {
@IBOutlet var collectionView: UICollectionView!
var cell : MyCollectionViewCell?
var names = ["Danial" , "dkfloza" , "Kosarifar" , "IOS" , "Learning", "sina" ]
var likes = ["23" , "7" , "17" , "100K" , "1000K" , "100"]
var dislikes = ["0","0","0","0","0","0"]
var playerViewController = AVPlayerViewController()
var playerView = AVPlayer()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .black
self.collectionView.delegate = self
let tap = UITapGestureRecognizer(target: self.cell?.myLabel, action:#selector(handleTap))
tap.numberOfTapsRequired = 1
cell?.myLabel.addGestureRecognizer(tap)
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return self.names.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
cell = collectionView.dequeueReusableCell(withReuseIdentifier: "id", for: indexPath as IndexPath) as! MyCollectionViewCell
// Use the outlet in our custom class to get a reference to the UILabel in the cell
cell?.myLabel?.text = self.names[indexPath.row]
cell?.myLabel?.textColor = .black
cell?.likes_num?.text = likes[indexPath.row]
cell?.dislike_num?.text = dislikes[indexPath.row]
cell?.likes_num?.textColor = .black
cell?.dislike_num?.textColor = .black
return cell!
}
//
//
// func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// // handle tap events
// print("You selected cell #\(indexPath.item)!")
//
//
//
//
// }
func handleTap(){
print("hello")
}
}
class MyCollectionViewCell : UICollectionViewCell{
//appClub
@IBOutlet var myLabel: UILabel!
//imagePlace
@IBOutlet var viewTesting: UIView!
//likes
@IBOutlet var likes_num: UILabel!
//dislikes
@IBOutlet var dislike_num: UILabel!
}
【问题讨论】:
-
您可以将按钮放在标签上,然后将它们自动布局为中心+等宽+等高,然后创建基于委托或闭包的操作;
-
这方面的最佳实践太多了。但是在每次练习中,您都必须自己处理
UITouch对象。尝试同时使用touches事件和集合视图委托。在集合视图(或您所在的单元格)中识别您正在触摸的项目(单元格)和触摸位置。稍后您可以在触摸项目的坐标系中映射该触摸位置以获取视图。 -
如果您尝试使用任何手势来完成您的工作,您可能会更改响应者(
UIResponder对象)层次结构。这会让你的情况变得更糟。
标签: ios uicollectionview uicollectionviewcell uitapgesturerecognizer