Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import UIKit
- class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
- let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
- override func viewDidLoad() {
- super.viewDidLoad()
- collectionView.dataSource = self
- collectionView.delegate = self
- collectionView.translatesAutoresizingMaskIntoConstraints = false
- collectionView.backgroundColor = .white
- collectionView.register(MyCollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
- view.addSubview(collectionView)
- NSLayoutConstraint.activate([
- collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
- collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
- collectionView.topAnchor.constraint(equalTo: view.topAnchor),
- collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
- ])
- DispatchQueue.main.asyncAfter(deadline: .now() + 10) { [weak self] in
- self?.collectionView.reloadData()
- print("collection reloaded")
- }
- }
- func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
- return 10
- }
- func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
- let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! MyCollectionViewCell
- cell.setup(value: indexPath.item)
- return cell
- }
- }
- class MyCollectionViewCell: UICollectionViewCell {
- let moreButton: UIButton!
- var value: Int = -1
- override init(frame: CGRect) {
- moreButton = UIButton()
- super.init(frame: frame)
- moreButton.setTitle("More", for: .normal)
- moreButton.menu = UIMenu(
- title: "More Menu",
- image: nil,
- identifier: nil,
- options: [],
- children: [
- UIAction(title: "Share") { [weak self] _ in
- guard let self else { return }
- print("Share \(self.value)")
- }
- ]
- )
- moreButton.showsMenuAsPrimaryAction = true
- backgroundColor = UIColor.lightGray
- addSubview(moreButton)
- moreButton.translatesAutoresizingMaskIntoConstraints = false
- NSLayoutConstraint.activate([
- moreButton.topAnchor.constraint(equalTo: topAnchor),
- moreButton.bottomAnchor.constraint(equalTo: bottomAnchor),
- moreButton.leadingAnchor.constraint(equalTo: leadingAnchor),
- trailingAnchor.constraint(equalTo: moreButton.trailingAnchor)
- ])
- }
- func setup(value: Int) {
- moreButton.setTitle("\(value)", for: .normal)
- self.value = value
- }
- required init?(coder aDecoder: NSCoder) {
- fatalError("init(coder:) has not been implemented")
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment