Я не знаю, с чего начать, у меня есть UICollectionView с несколькими ячейками, заполненными UIImage. Я хочу, чтобы каждая ячейка/UIImage выполняла различное действие при касании пальцем. Может ли кто-нибудь указать мне правильное направление здесь?
Действие, которое у меня есть, - это @IBAction из UIButton, я знаю, что хочу, чтобы это действие было в ячейке в UICollectionView..
(Думаю, мне нужно что-то сделать с «let cell = countryCollectionView.dequeueReusableCell»?
import UIKit
class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
@IBOutlet weak var soundsCollectionView: UICollectionView!
lazy var cv: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
var cc = UICollectionView(frame: .zero, collectionViewLayout: layout)
cc.translatesAutoresizingMaskIntoConstraints = false
cc.register(CustomCell.self, forCellWithReuseIdentifier: "CustomCell")
cc.delegate = self
cc.dataSource = self
cc.backgroundColor = .white
return cc
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.addSubview(cv)
cv.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
cv.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
cv.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
cv.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell
cell.tag = indexPath.row
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: 100)
}
}
class CustomCell: UICollectionViewCell {
lazy var centerImageView: UIImageView = {
var img = UIImageView()
img.translatesAutoresizingMaskIntoConstraints = false
img.image = UIImage(named: "1")
img.clipsToBounds = true
img.isUserInteractionEnabled = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handler(_:)))
tapGesture.numberOfTapsRequired = 1
img.addGestureRecognizer(tapGesture)
return img
}()
@objc private func handler(_ sender: UITapGestureRecognizer) {
print("tapped tag > ", self.tag)
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(centerImageView)
centerImageView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
centerImageView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
centerImageView.heightAnchor.constraint(equalToConstant: 80).isActive = true
centerImageView.widthAnchor.constraint(equalToConstant: 80).isActive = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
@IBAction func sound1(_ sender: UIButton) { if (self.tag == 0) { // I am first cell, so act like this. } else if (self.tag == 1) { // Second cell blah blah } }
Но как мне настроить каждую ячейку по-разному, чтобы что-то делать одним касанием? Например image1: print (я кнопка 1) И image2: print (я кнопка 2) Еще раз, спасибо за ваше время! Очень ценится - person DeDe Schurk   schedule 13.07.2020UITapGestureRecognizer
дляUIImageView
вUICollectionViewCell
. В жесте касания#action
отметьтеself.tag
, чтобы вы могли обработать это, еслиtag == 0
это изображение первой ячейки. а еслиtag == 3
это 4. ячейка. Вы не возражали? - person eemrah   schedule 13.07.2020let tap = UITapGestureRecognizer(target: self, action: #selector(doubleTapped)) tap.numberOfTapsRequired = 2 view.addGestureRecognizer(tap)
в свой ViewController (viewDidLoad). И@objc func doubleTapped() { // do something here }
Но я не понимаю, что вы имеете в виду подself.tag
. Я на правильном пути с приведенным выше кодом? Еще раз спасибо Элия! - person DeDe Schurk   schedule 15.07.2020UICollectionViewCell
тегу, и этот тег поможет тебе, какая ячейка является элементом внутриUICollectionViewCell
. Я редактирую свой ответ в качестве примера для вас - person eemrah   schedule 15.07.2020img.image = UIImage(named: "1")
для кода, эта строка говорит, что у вас должно быть изображение с именем1
. поэтому вы должны использовать свои собственные имена изображений, возможно? - person eemrah   schedule 20.07.2020let imageArray = [UIImage(named:"first"),UIImage(named:"second"),UIImage(named:"third"),UIImage(named:"fourth")]
и в методеcellForRow
вам нужно вызватьmyCell.imageView.image = imageArray[indexPath.row]
или то, как вы обрабатываете свою ячейку. Для моего примера в ответе это должно бытьcell.centerImageView.image = imageArray[indexPath.row]
. вам нужно выяснить, что ``numberOfCount` должно равнятьсяimageArray
count - person eemrah   schedule 20.07.2020cellForRow
? у меня нет..? Вы имеете в видуcellForItemAt
? - person DeDe Schurk   schedule 20.07.2020cellForItemAt
:) - person eemrah   schedule 20.07.2020func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell cell.centerImageView.image = countries[indexPath.row] cell.tag = indexPath.row return cell }
- person DeDe Schurk   schedule 20.07.2020