0

enter image description here 저는 신속하게 프로젝트를하고 있습니다. 콜렉션 뷰를 정의하고 셀을 사용자 정의하여 이미지가 아래처럼 보이게 만듭니다. 자, 일단 셀을 클릭하면, 제 기능은 어떤 셀을 클릭했는지를 알려주지 만 더 자세한 정보를 얻고 싶습니다. 예를 들어 셀 번호 2의 그림을 얻습니다. 그 목적을 위해 탭 제스처를 정의하려고 시도했지만 작동하지 않는 것 같습니다. 여기에 내 모든 코드 :UICollectionView에서 사용자 정의 된 셀의 어떤 부분을 클릭했는지 알아 보는 방법은 무엇입니까?

수입 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! 











} 
+1

레이블에 단추를 넣고 가운데와 같은 너비 + 높이의 단추를 자동 레이아웃 한 다음 대리자 또는 클로저 기반 동작을 만들 수 있습니다. – SeanLintern88

+1

여기에는 너무 많은 우수 사례가 있습니다. 그러나 각각의 연습에서 자신 만의 'UITouch'객체를 처리해야합니다. 'touches' 이벤트와 콜렉션 뷰 델리게이트를 함께 사용해보십시오. 터치 된 항목 (셀)과 콜렉션 뷰에서의 터치 위치 (또는 셀까지)를 식별하십시오. 나중에 해당 터치 위치를 터치 된 항목의 좌표계에 매핑하여 뷰를 가져올 수 있습니다. –

+1

작업을 수행하기 위해 제스처를 사용하려고하면, 응답자 ('UIResponder' 개체) 계층을 변경할 수 있습니다. 이것은 당신을 위해 상황을 악화시킬 것입니다. –

답변

0

->

override func viewDidLoad() { 
     super.viewDidLoad() 

     let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap)) 
     tap.delegate = self 
     tap.numberOfTapsRequired = 1 
     tap.numberOfTouchesRequired = 1 
     tableView.addGestureRecognizer(tap) 
    } 

테이블보기에 제스처를 추가 ->이 탭 감지

func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { 
    let tableView = gestureRecognizer.view as! UITableView 
    let point: CGPoint = gestureRecognizer.location(in: tableView) 
    if (tableView.indexPathForRow(at: point) != nil) { 
     return true; 
    } 
    return false; 
} 

-> 셀의 위치를 ​​찾고 su에 태그를 지정합니다. bview보기 (예 : imageView, label) 정확한 뷰를 얻을 수 있습니다.

public func handleTap(tap: UITapGestureRecognizer) 
{ 
    if (UIGestureRecognizerState.ended == tap.state) { 
     let tableView = tap.view as! UITableView 
     let point: CGPoint = tap.location(in: tableView) 
     let indexPath = tableView.indexPathForRow(at: point) 
     tableView.deselectRow(at: indexPath!, animated: false) 
     let cell = tableView.cellForRow(at:indexPath!) 
     let pointInCell = tap.location(in: cell) 
     if ((cell?.imageView?.frame)!.contains(pointInCell)) { 
      // user tapped image 
     } else { 
      // user tapped cell 
     } 
    } 
} 
+0

나는 tableView에서 CollectionView로 주어진 코드를 변환하려고합니다. 'if ((cell? .imageView? .frame) !. contains (pointInCell))''셀? '이후에 보이는 것입니다. 레이블이나 같은 셀에있는 요소 중 하나를 사용할 수 없습니다. imageView 또는 .... 탭 감지에 대한 BTW 셀렉터는'#selector (self.handleTap (tap :)) '여야합니다. 그렇지 않으면 모호한 사용에 대한 컴파일 오류가 발생합니다 :) –

+0

이제는 문제가 무엇입니까? 레이블 셀에 액세스 할 수 없습니까? .myLabel? 셀 클래스에서 public 또는 internal로 정의 된 속성에 액세스 할 수 있습니다. – Saurav