如何让 imageView 占用 CollectionView 单元格?

Posted

技术标签:

【中文标题】如何让 imageView 占用 CollectionView 单元格?【英文标题】:How do I get an imageView to take up a CollectionView Cell? 【发布时间】:2019-12-27 02:53:14 【问题描述】:

我有以下困境:

单元格的尺寸正确,但 imageView 没有填满单元格。我尝试通过控制从 imageView 拖动到单元格来向 imageView 添加约束。

这仍然没有填充单元格内的 imageView。

我必须陈述更多事实,因为由于代码转储,我的帖子主要是代码。基本上, 我想用 imageView 填充 CollectionView 单元格,但即使在我设置约束后它也不起作用。从红色可以看出,imageView 不占用约束。如何设置图像视图以占用约束?

这里是完整的代码:

//
//  ProfileViewController.swift
//  TheBiggestBlunt
//
//  Created by Nick Steen on 12/16/19.
//  Copyright © 2019 Nick Steen. All rights reserved.
//

import UIKit
import SwiftUI
import Firebase
import FirebaseUI
import SwiftKeychainWrapper

class ProfileViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout

    @IBOutlet weak var collectionview: UICollectionView!

    @IBOutlet weak var navBarName: UINavigationItem!


   //var posts = [Post]()

//    var sentUserID : String = ""
//    var sentUsername: String = ""
    var posts2 = [Post]()

    var following = [String]()
    var xOffset = [0,138,276]
    var yOffset = 500
    var i = 0
    //var posts1 = [String]()
    var userStorage: StorageReference!
    var ref : DatabaseReference!


    override func viewDidLoad() 
        super.viewDidLoad()
        collectionview.delegate = self
        collectionview.dataSource = self
        navBarName.title = sentUsername







        // 1
        fetchPosts()
        (collectionview.collectionViewLayout as! UICollectionViewFlowLayout).itemSize = CGSize(width: 138, height: 138)
        //displayImages()
        // 5
    
//    func displayImages()
//        for post in posts2
//            //let imageName = post.pathToImage
//            //let image = UIImage(named: imageName!)
//            let imageView = UIImageView()
//            imageView.sd_setImage(with: URL(string: post.pathToImage))
//
//            imageView.frame = CGRect(x: xOffset[i%3], y: yOffset, width: 137, height: 137)
//
//            scrollView.addSubview(imageView)
//
//            if(i%3 == 2)
//                yOffset = yOffset + 138
//            
//
//            i = i + 1
//        
//        scrollView.contentSize = CGSize(width:414, height:yOffset+137);
//    

    func fetchPosts() 
        // 2
        let uid = Auth.auth().currentUser!.uid
        let ref = Database.database().reference().child("posts")
        let uids = Database.database().reference().child("users")
        // 3
        uids.observe( DataEventType.value, with:  (snapshot) in
            // 6
            let dict = snapshot.value as! [String:NSDictionary]
            for (_,value) in dict 
                if let uid = value["uid"] as? String
                    self.following.append(uid)

                
            
            // 7
            ref.observe( DataEventType.value, with:  (snapshot2) in
                // 9
                //dictionary of posts
                let dict2 = snapshot2.value as! [String:NSDictionary]
                //go through all the user ids from uids.observe call
                for(key, value) in dict

                    //for each uid in the following dictionary
                    for uid2 in self.following
                        //if the posts belong to a user the user is following
                        if (uid2 == key)

                            for (key2,value2) in dict2 
                                for(key3, value3) in value2 as! [String:NSDictionary]
                                    let post = Post()
                                   if let author = value3["author"] as? String, let likes = value3["likes"] as? Int, let pathToImage = value3["pathToImage"] as? String, let postID = value3["postID"] as? String, let userID = value3["userID"] as? String

                                    post.author = author
                                    post.likes = likes
                                    post.pathToImage = pathToImage
                                    post.postID = postID
                                    post.userID = userID
                                    self.posts2.append(post)




                                    //print(value3)
                                    
                                
                                //print(key2 + "this is key2")

                                    let urlimage = value2
                                    //print(urlimage)
                                    //self.posts1.append(urlimage)

                                    //self.posts1.append(posst)
                                

                        
                        
                    
                //self.displayImages()

                self.collectionview.reloadData()

                // 10
            )


            // 8
        )

        // 4
    


    func numberOfSections(in collectionView: UICollectionView) ->Int 

        return 1
    

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 

        return posts2.count

    

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

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PostCell", for: indexPath) as! PostCell
        //cell.postImage.sd_setImage(with: URL(string: posts1[indexPath.row]))

        cell.postImage.sd_setImage(with: URL(string: posts2[indexPath.row].pathToImage))

        cell.postImage.contentMode = .scaleAspectFit

        cell.backgroundColor = .red
        //creating the cell
        //cell.postImage.downloadImage(from: self.posts[indexPath.row])
//        let storageRef = Storage.storage().reference(forURL: self.posts[indexPath.row].pathToImage)


//
//


        //let stickitinme = URL(fileURLWithPath: posts1[0])
        //cell.postImage.sd_setImage(with: stickitinme)

        //cell.authorLabel.text = self.posts[indexPath.row].author
        //cell.likeLabel.text = "\(self.posts[indexPath.row].likes) Likes"


        return cell
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 

        let yourWidth = (collectionView.frame.width - 4)/3
        let yourHeight = yourWidth
        print("is called sizeForItemAt")

        return CGSize(width: yourWidth, height: yourHeight)


    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets 
        //return UIEdgeInsets.zero
        print("is called insetForSectionAt")
        return UIEdgeInsets(top: 0,left: 0,bottom: 0,right: 0);

    

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat 
        print("is called interim")
        return 1.0
    

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat 
        print("is called line spacing")
        return 1.0
    
//

    @IBAction func signOutPressed(_sender: Any)
           signOut()
           self.performSegue(withIdentifier: "toSignIn", sender: nil)
       

    @objc func signOut()
           KeychainWrapper.standard.removeObject(forKey:"uid")

           do
               try Auth.auth().signOut()
            catch let signOutError as NSError
               print("Error signing out: %@", signOutError)
           
           dismiss(animated: true, completion: nil)
       

【问题讨论】:

【参考方案1】:

在 UICollectionViewCell 中放置一个 ImageView 并将Leading、Trailing、Top、Bottom 约束设置为零(0)

【讨论】:

试过了,还是不行。我需要额外的限制吗? 之前的约束删除了吗? 填充比例使它们看起来比以前更小。我删除了约束。你确定不应该有约束吗? 对不起。 ImageView 的内容模式没有问题。只有前导、尾随、顶部和底部约束才能起作用。 所有这些约束都已应用,但问题仍然存在。我对此感到非常困惑!

以上是关于如何让 imageView 占用 CollectionView 单元格?的主要内容,如果未能解决你的问题,请参考以下文章

回收ImageView占用的图像内存

android 如何重写imageview 让图片有圆角效果

如何让 UITableViewCell 中的 imageView 大小固定

iOS开发 在imageView不变的情况下,让imageView里的图片旋转90°

如何让我的imageview旋转到iPhone中心的视角?

如何自动中心裁剪ImageView Android?