swift 如何将单元格从一个collectionView添加到另一个collectionView

wgx48brx  于 2023-05-05  发布在  Swift
关注(0)|答案(1)|浏览(171)

我有一个集合视图与数据从API。
在单元格中有一个按钮,它应该将单元格添加到另一个名为收藏夹的collectionView中
我怎么能移动那个
我曾试图添加额外的选项,我的模型,以找到收藏夹的每一个元素标记,但它不起作用

// MARK: - Movie
struct Movie: Codable {
    let resultCount: Int?
    let favorite: Bool?
    let results: [Results]?
}

// MARK: - Result
struct Results: Codable {
    let wrapperType: WrapperType?
    let kind: Kind?
    let collectionID, trackID: Int?
    let artistName, collectionName, trackName, collectionCensoredName: String?
    let trackCensoredName: String?
    let collectionArtistID: Int?
    let collectionArtistViewURL, collectionViewURL, trackViewURL: String?
    let previewURL: String?
    let artworkUrl30, artworkUrl60, artworkUrl100: String?
    let collectionPrice, trackPrice, trackRentalPrice, collectionHDPrice: Double?
    let trackHDPrice, trackHDRentalPrice: Double?
    let releaseDate: String?
    let collectionExplicitness, trackExplicitness: Explicitness?
    let discCount, discNumber, trackCount, trackNumber: Int?
    let trackTimeMillis: Int?
    let country: Country?
    let currency: Currency?
    let primaryGenreName: PrimaryGenreName?
    let contentAdvisoryRating: ContentAdvisoryRating?
    let longDescription: String?
    let hasITunesExtras: Bool?
    let shortDescription: String?
    let artistID: Int?
    let artistViewURL: String?

}

class MainViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

let networkService = NetworkService()
var movie: Movie? = nil

let collectionView = UICollectionView(frame: .zero,
                               collectionViewLayout: UICollectionViewFlowLayout()
)

override func viewDidLoad() {
    super.viewDidLoad()
        setupCollectionView()
    
    let url = "https://itunes.apple.com/search?term=movie"
    networkService.request(URL: url) { [self] (result) in
        switch result {
        case .success(let movie):
            self.movie = movie
            collectionView.reloadData()
        case .failure(let error):
            print("error", error)
        }
    }
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    collectionView.frame = view.bounds
    
    
    }
    



        
       
func setupCollectionView() {
    collectionView.register(CustomCollectionViewCell.self, forCellWithReuseIdentifier: "identifier")
    collectionView.dataSource = self
    collectionView.delegate = self
    view.addSubview(collectionView)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 10    }
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 1    }

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: view.frame.size.width/3 - 4, height: view.frame.size.width/2)
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return (movie?.results?.count) ?? 0
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifier", for: indexPath) as! CustomCollectionViewCell
    cell.contentView.layer.cornerRadius = 15
    cell.imageView.downloaded(from: (movie?.results![indexPath.row].artworkUrl100)!)
    return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let DetailsVC = DetailsViewController()
    self.navigationController?.pushViewController(DetailsVC, animated: true)
    DetailsVC.imageView.downloaded(from: (movie?.results![indexPath.row].artworkUrl100)!)
    DetailsVC.yearLabel.text = " Год выпуска: \(movie?.results![indexPath.row].releaseDate ?? "")"
    DetailsVC.nameLabel.text = (movie?.results![indexPath.row].trackName)
    DetailsVC.genreLabel.text = (movie?.results![indexPath.row].primaryGenreName?.rawValue)
    DetailsVC.producerLabel.text = (movie?.results![indexPath.row].artistName)
    DetailsVC.descritionLabel.text = (movie?.results![indexPath.row].longDescription)
}

}

class NetworkService {

func request(URL url:String, completion: @escaping (Result<Movie, Error>) -> Void) {
    guard let url = URL(string: url) else { return }
    URLSession.shared.dataTask(with: url) {(data, response, error) in
        DispatchQueue.main.async {
            if let error = error {
                print("Some error")
                completion(.failure(error))
                return
            }
            guard let data = data else { return }
            do {
                let movies = try
                JSONDecoder().decode(Movie.self, from: data)
                completion(.success(movies))
            } catch let JsonError{
                print("Failed to decode JSON", JsonError)
                completion(.failure(JsonError  ))
        
            }
        }
    }.resume()
}

}
类CustomCollectionViewCell:UICollectionViewCell {

let imageView: UIImageView = {
    let iv = UIImageView()
    iv.clipsToBounds = true
    iv.contentMode = .scaleAspectFill
    return iv
}()
let likeButton: UIButton = {
    let button = UIButton()
    button.setImage(UIImage(named: "heart"), for: .normal)
    return button
}()
override init(frame: CGRect) {
    super.init(frame: frame)
    //button
    self.contentView.addSubview(likeButton)
    likeButton.layer.zPosition = 1
    likeButton.snp.makeConstraints{ make in
        make.right.equalTo(-10)
        make.top.equalTo(10)
        make.width.equalTo(30)
        make.height.equalTo(30)
    }
    likeButton.addTarget(self, action: #selector(likeTapped), for: .touchUpInside)
    //setup cell
    self.contentView.layer.cornerRadius = 16
    self.contentView.clipsToBounds = true
    self.layer.shadowColor = UIColor.black.cgColor
    self.layer.shadowOpacity = 1.0
    self.layer.shadowOffset = .zero
    self.layer.shadowRadius = 4.0
    self.layer.shouldRasterize = true
    self.layer.rasterizationScale = UIScreen.main.scale
    self.layer.drawsAsynchronously = true
    self.layer.masksToBounds = false
    
    // Image setup
    self.contentView.addSubview(imageView)
    imageView.contentMode = .scaleAspectFill
    imageView.snp.makeConstraints{ make in
        make.left.equalTo(0)
        make.right.equalTo(0)
        make.width.equalTo(contentView)
        make.height.equalTo(contentView)
    }
    
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
@objc func likeTapped() {
    if likeButton.tag == 0 {
        likeButton.setImage(UIImage(named: "redheart"), for: .normal)
        likeButton.tag = 1
        
    } else {
        likeButton.setImage(UIImage(named: "heart"), for: .normal)
        likeButton.tag = 0
    }
        
    }

}
是否可以只在我模型中添加变量favorite来显示另一个collectionView中的数据?事情是控制这些移动的按钮被放置在CustomCollectionViewCell中

xmjla07d

xmjla07d1#

你需要重新思考这个问题。
你不能“将单元格添加到另一个集合视图”。您将更新其他集合视图显示的模型。
您需要弄清楚应用的数据模型是如何设置的。一种可能性是为模型中的条目添加“is favorite”标志,并让favorites视图控制器过滤模型以显示标记为favorites的条目。当用户单击另一个视图控制器中的按钮时,您将更新模型以将该条目标记为收藏夹,然后向另一个视图控制器发送某种类型的通知,告知模型已更改。(它可以是广播的“模型已更改”通知,或者您可以制作一个更有针对性的“项目xyz添加到收藏夹”消息)。
我没有代码给予你,因为它将是特定于您的应用程序。

相关问题