如何获取imageView来占用CollectionView单元格?

问题描述 投票:0回答:1

我有以下困境:enter image description here

单元格的尺寸正确,但是imageView不能填满单元格。我试图通过将控件从imageView拖动到单元格来向imageView添加约束。enter image description here

这仍然不会填充单元格中的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)
       }

ios swift uicollectionview uicollectionviewcell
1个回答
0
投票

将ImageView拖放到UICollectionViewCell内,并将Leading,Trailing,Top,Bottom约束设置为零(0)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.