UICollectionView에서 여러 이미지를 선택하고 다른 뷰 컨트롤러로 전송하는 방법은 무엇입니까?

다니

코드는 Swift로 작성되었습니다. 사용자가 게시물을 올릴 수있는 소셜 앱을 만들고 있습니다. Firebase를 백엔드 (데이터베이스, 저장소)로 사용하고 있습니다. 따라서 UICollectionView장치의 사진 라이브러리에서 모든 사진을 가져오고 사용자 지정 셀을 사용하여 컬렉션보기를 채 웁니다. 동일한 View 컨트롤러에 사용자가 사진을 찍고 게시물을 만드는 데 사용할 수있는 또 다른 사용자 지정 셀이 있습니다. 더 명확하게하려면 :

  • 사용자가 사진을 찍기로 결정한 경우 "사진 사용"을 클릭하면 방금 찍은 사진을 다른 옵션 (예 : UITextFields&를 사용하는 제목, 설명 및 태그 UITextView) 과 함께 표시해야하는 새 뷰 컨트롤러에 표시되어야합니다. .

  • 사용자가 자신의 라이브러리에서 여러 장의 사진을 선택하기로 결정하면 어떻게 든 해당 사진 / 셀을 표시하고 (즉, 확인 표시 버튼을 사용하여) 선택한 사진을 배열에 추가해야합니다 (일부 제한은 10 장 정도). "Next"버튼을 클릭하면 배열을 New Post View Controller로 보내야합니다. 여기서 모든 이미지는 수평 UICollectionView(?!)을 사용하여 동적으로 표시되어야합니다 (우연히 선택한 경우 이미지를 제거하는 옵션 포함). ) 위와 같이 제목, 설명 등을 추가 할 수있는 기회가 있습니다. 이제 어떻게해야할지 모르겠습니다.

나는 해결책을 찾았지만 지금은 며칠 동안 이것에 갇혀 있으므로 도움을 대단히 환영합니다!

Collection View 컨트롤러에있는 내용은 다음과 같습니다 (PS : 사진에서 이미지를 가져 오는 기능이있는 부분은 포함하지 않았습니다).

import UIKit
import Photos

class PrePhotoPostVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UICollectionViewDelegateFlowLayout {

@IBOutlet weak var nextButton: UIBarButtonItem!
var photosLibraryArray = [UIImage]()

@IBOutlet weak var collectionView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()

    checkPhotoLibraryPermission()
    setupCollectionViewDelegates()
}

@IBAction func cancelButtonPressed (_ sender: UIBarButtonItem) {
    dismiss(animated: true, completion: nil)
}

@IBAction func nextButtonPressed (_ sender: UIBarButtonItem) {
    nextButton.isEnabled = false
}

@IBAction func takeAphotoButtonPressed (_ sender: UIButton) {

    // Camera Autorization
    AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo) { response in
        if response {
            if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
                let imagePicker = UIImagePickerController()
                imagePicker.delegate = self
                imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
                imagePicker.allowsEditing = false
                self.present(imagePicker, animated: true, completion: nil)
            }
            else {
                print("Camera isn't available in similator")
            }
        }
        else {
            print("unautorized")
        }
    }
}

 func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 2
}
 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if section == 0 {
        return 1
    } else {
        return photosLibraryArray.count
    }
 }

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if indexPath.section == 0 {
        let cellCamera = collectionView.dequeueReusableCell(withReuseIdentifier: cellPrePostCameraCell, for: indexPath) 
        return cellCamera
    }
    else {
        let cellPhotoLibrary = collectionView.dequeueReusableCell(withReuseIdentifier: cellPrePostPhotoLibrary, for: indexPath) as! PrePhotoPostPhotoLIbraryCell
        cellPhotoLibrary.awakeFromNib()
        cellPhotoLibrary.photoLibraryImage.image = photosLibraryArray[indexPath.row]
        return cellPhotoLibrary
    }
}
}

이것이 어떻게 생겼는지에 대한 스크린 샷 UICollectionView:

여기에 이미지 설명 입력

다음은 사진 라이브러리 셀의 코드입니다.

import UIKit

class PrePhotoPostPhotoLIbraryCell: UICollectionViewCell {

    // MARK: Outlets
    @IBOutlet weak var photoLibraryImage: UIImageView!

    // var selectedPhotos = [UIImageView]()

    @IBAction func selectedButtonPressed(_ sender: UIButton) {
        self.layer.borderWidth = 3.0
        self.layer.borderColor = isSelected ? UIColor.blue.cgColor : UIColor.clear.cgColor
    }
    override func awakeFromNib() {

        photoLibraryImage.clipsToBounds = true
        photoLibraryImage.contentMode = .scaleAspectFill
        photoLibraryImage.layer.borderColor = UIColor.clear.cgColor
        photoLibraryImage.layer.borderWidth = 1
        photoLibraryImage.layer.cornerRadius = 5

    }
}
매디

먼저 선택한 셀 항목을 저장할 가변 유형의 배열을 선언하십시오.

var _selectedCells : NSMutableArray = []

그런 다음 viewDidLoad 함수 에서 아래 코드를 추가하십시오.

 override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        //this will allow multiple selection on uicollectionviewcell
        CollectionView.allowsMultipleSelection=true //CollectionView is your CollectionView outlet
}

그런 다음 셀 선택 및 선택 취소를위한 collectionview의 위임 기능 구현

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){

        //add the selected cell contents to _selectedCells arr when cell is selected
        _selectedCells.add(indexPath)
        collectionView.reloadItems(at: [indexPath])
    }

    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {

        //remove the selected cell contents from _selectedCells arr when cell is De-Selected

        _selectedCells.remove(indexPath)
        collectionView.reloadItems(at: [indexPath])
    }

선택한 항목의 NSIndexPath를 배열에 저장 한 다음 대리자 함수에서 비교 기준으로 사용하는 것이 좋습니다 cellForItemAt indexPath.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YOUR_CELL_Identifier", for: indexPath as IndexPath)

//add your tick mark image to the cell in your storyboard or xib file.
let tickImage = cell.viewWithTag(YOUR_IMAGE_TAG_HERE) as? UIImageView

//Show tickImage if the cell is selected and hide tickImage if cell is NotSelected/deSelected.or whatever action you want to perform in case of selection and deselection of cell.

if _selectedCells.contains(indexPath) {
cell.isSelected=true
collectionView.selectItem(at: indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition.top)
tickImage?.isHidden=false
}
else{
cell.isSelected=false
tickImage?.isHidden=true
}
return cell
}

다음 컨트롤러로 항목을 보내려면 선택한 인덱스 경로에서 모든 항목을 가져옵니다.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관