새소식

iOS/UIKit

[UIKit][코드 베이스]CollectionView Context Menus

  • -

[참고 영상]

https://youtu.be/a1Agazw2JxM


[학습 목표]

UIKit에서 코드베이스를 이용해서 ContextMenu를 만들어 보자!

(해당 학습에서 쓰는 모든 이미지의 저작권은 각 이미지의 저작권자한테 있습니다.)


[구현 방법]

1. 우선은 ContextMenu를 만들기 이전에 Collection View를 먼저 만들어보도록 하자.

1 - 1. asset에 원하는 이미지를 6개 넣고(만일 원한다면 추가로 더 넣거나 빼고 imageNames  Array에서 1부터 이미지 넣은 숫자만큼으로 수정해주자.) 이름을 image숫자로 지정해주자.

1 - 2. 코드베이스를 활용해서 collectionview를 구현하자.

<collection view 구현>

import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    let imageNames = Array(1...6).map { "image\($0)" }
    
    private let collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 2
        layout.minimumInteritemSpacing = 2
        layout.scrollDirection = .vertical
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .systemBackground
        collectionView.register(ImageCollectionViewCell.self, forCellWithReuseIdentifier: ImageCollectionViewCell.identifier)
        return collectionView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(collectionView)
        collectionView.delegate = self
        collectionView.dataSource = self
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        collectionView.frame = view.bounds
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageNames.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ImageCollectionViewCell.identifier, for: indexPath) as? ImageCollectionViewCell else{
            fatalError()
        }
        
        cell.imageView.image = UIImage(named: imageNames[indexPath.row])
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: (view.frame.self.width / 2) - 4, height: (view.frame.self.width / 2) - 4 )
    }
    
}

class ImageCollectionViewCell: UICollectionViewCell {
    static let identifier = "ImageCollectionViewCell"
    
    let imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.clipsToBounds = true
        imageView.contentMode = .scaleAspectFill
        return imageView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(imageView)
    }
    
    required init?(coder: NSCoder) {
        fatalError()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        imageView.frame = contentView.bounds
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
        imageView.image = nil
    }
}

 

2. 이제 해당 collectionView안에 넣어질 ContextMenu를 구현하도록 하자.

<ContextMenu와 해당 ContextMenu에 Open 기능이 넣어진 코드>

    func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemsAt indexPaths: [IndexPath], point: CGPoint) -> UIContextMenuConfiguration? {
        
        let config = UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { _ in
            
            let open = UIAction(title: "Open",
                                image: UIImage(systemName: "link"),
                                identifier: nil,
                                discoverabilityTitle: nil,
                                attributes: .disabled,
                                state: .off
            ){ _ in
                print("Tapped open")
            }
            return UIMenu(
                title: "",
                image: nil,
                identifier: nil,
                options: UIMenu.Options.displayInline,
                children: [open]
            )
        }
        return config
    }
}

 

3. 만일 기능을 추가로 더 원한다면 UIMenu 밑의 Children에 추가해줄 기능들을 만들어주자.

 

<기능 추가 코드>

let open = UIAction(
    title: "Open",
    image: UIImage(systemName: "link"),
    identifier: nil,
    discoverabilityTitle: nil,
    //attributes: .disabled,
    state: .off
){ _ in
    print("Tapped open")
}

let favorite = UIAction(
    title: "Open Favtoprite",
    image: UIImage(systemName: "magnifyingglass"),
    identifier: nil,
    discoverabilityTitle: nil,
    //attributes: .disabled,
    state: .off
){  _ in
    print("Tapped favorite")
}

let copy = UIAction(
    title: "Open copy",
    image: UIImage(systemName: "link"),
    identifier: nil,
    discoverabilityTitle: nil,
    //attributes: .disabled,
    state: .off
){ _ in
    print("Tapped copy")
}

return UIMenu(

    title: "Action",
    subtitle: "",
    image: nil,
    identifier: nil,
    options: UIMenu.Options.displayInline,
    children: [open,favorite,copy]
)

 

 

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.