首页 > 解决方案 > UIScrollView:当从 firebase 调用用户名时,在滚动视图中显示用户个人资料图像

问题描述

我正在构建一个应用程序,用户在其中选择他们关注的 4 个随机用户来回答问题。目前它从我的 firebase 数据库中调用随机名称。每个用户都有一个他们在注册时上传的个人资料图片,这与用户全名保存在同一位置。

我希望与全名同时调用配置文件图像,并按名称被调用的顺序显示在屏幕的 UIScrollView 上(例如,首先显示选项 A 用户图像,然后滚动到选项 B 用户图像等) -像这张图片

到目前为止,全名被调用并显示在按钮上,我可以访问 URL 的 firebase 存储,但我不知道如何从 firebase 获取 profileImageUrl,以便在选择用户名时在滚动视图上按此顺序显示随机,到目前为止我有这个:

@IBOutlet weak var pinionImagesScrollView: UIScrollView!
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var optionA: UIButton!
@IBOutlet weak var optionB: UIButton!
@IBOutlet weak var optionC: UIButton!
@IBOutlet weak var optionD: UIButton!

        let numberOfKeys = randomKeyArray.count
        var namesRemaining = numberOfKeys
        var names = [String]()
        var profileImages = [String]()

        for i in 0..<numberOfKeys {
            let thisUserKey = randomKeyArray[i]
            let userRef = self.ref.child("users").child(thisUserKey)
            userRef.observeSingleEvent(of: .value, with: { snapshot in
                let name = snapshot.childSnapshot(forPath: "fullname").value as! String
                let profileImageUrl = snapshot.childSnapshot(forPath: "profileImageUrl").value as! String
                print(name)
                namesRemaining -= 1
                names.append(name)

                // Another array for images
                print(profileImageUrl)
                profileImages.append(profileImageUrl)

                self.currIds.append(thisUserKey)
                if namesRemaining == 0 {
                    self.currNames = names
                    self.optionA.setTitle(names[0], for: .normal)
                    self.optionA.backgroundColor = UIColor.orange
                    self.optionB.setTitle(names[1], for: .normal)
                    self.optionB.backgroundColor = UIColor.orange
                    self.optionC.setTitle(names[2], for: .normal)
                    self.optionC.backgroundColor = UIColor.orange
                    self.optionD.setTitle(names[3], for: .normal)
                    self.optionD.backgroundColor = UIColor.orange
                }
            })
        }

将不胜感激任何帮助/解释,谢谢:)

编辑代码更新:

@IBOutlet weak var imagePageControl: UIPageControl!
@IBOutlet weak var userImageScrollView: UIScrollView!
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var optionA: UIButton!
@IBOutlet weak var optionB: UIButton!
@IBOutlet weak var optionC: UIButton!
@IBOutlet weak var optionD: UIButton!

var user: UserModel?

override func viewDidLoad() {
    super.viewDidLoad()
    loadNewQuestion()
    getFourRandomNodesAndPrintUserName()
    imagePageControl.numberOfPages = namesWithUrl.count
    setupLayout()
}


var ref: DatabaseReference = Database.database().reference()
var currNames: [String] = []
var currIds: [String] = []
var names = [String]()
var namesWithUrl = [String : String]()
var frame = CGRect(x: 0, y: 0, width: 0, height: 0)
var imageViewA = UIImageView()
var imageViewB = UIImageView()
var imageViewC = UIImageView()
var imageViewD = UIImageView()

func setupLayout() {

    userImageScrollView.addSubview(imageViewA)
    imageViewA.translatesAutoresizingMaskIntoConstraints = false
    imageViewA.widthAnchor.constraint(equalTo: userImageScrollView.widthAnchor, constant: -10).isActive = true
    imageViewA.heightAnchor.constraint(equalToConstant: 60).isActive = true
    imageViewA.topAnchor.constraint(equalTo: userImageScrollView.topAnchor, constant: -5).isActive = true

    userImageScrollView.addSubview(imageViewB)
    imageViewB.translatesAutoresizingMaskIntoConstraints = false
    imageViewB.widthAnchor.constraint(equalTo: userImageScrollView.widthAnchor, constant: -10).isActive = true
    imageViewB.heightAnchor.constraint(equalToConstant: 60).isActive = true
    imageViewB.topAnchor.constraint(equalTo: imageViewA.bottomAnchor, constant: 5).isActive = true

    userImageScrollView.addSubview(imageViewC)
    imageViewC.translatesAutoresizingMaskIntoConstraints = false
    imageViewC.widthAnchor.constraint(equalTo: userImageScrollView.widthAnchor, constant: -10).isActive = true
    imageViewC.heightAnchor.constraint(equalToConstant: 60).isActive = true
    imageViewC.topAnchor.constraint(equalTo: imageViewB.bottomAnchor, constant: 5).isActive = true

    userImageScrollView.addSubview(imageViewD)
    imageViewD.translatesAutoresizingMaskIntoConstraints = false
    imageViewD.widthAnchor.constraint(equalTo: userImageScrollView.widthAnchor, constant: -10).isActive = true
    imageViewD.heightAnchor.constraint(equalToConstant: 60).isActive = true
    imageViewD.topAnchor.constraint(equalTo: imageViewC.bottomAnchor, constant: 5).isActive = true
    imageViewD.bottomAnchor.constraint(equalTo: userImageScrollView.bottomAnchor, constant: -5).isActive = true
}

   // Each view is attached to the bottom of the previous view, and the final must be attached to the bottom of the scroll view in order for it to scroll properly.

func getFourRandomNodesAndPrintUserName() {
    self.currNames = []
    self.currIds = []

    var myKeyArray = [String]()
    guard let uid = Auth.auth().currentUser?.uid else {
        return
    }

    let ref = self.ref.child("following").child(uid)
    //retreives all nodes in the following node
    ref.observeSingleEvent(of: .value, with: { snapshot in
        print(snapshot.children.allObjects)
        for child in snapshot.children { //build the array of keys
            let snap = child as! DataSnapshot
            let key = snap.key
            myKeyArray.append(key)
        }

        var randomKeyArray = [String]()
        let numFollowers = min(4, myKeyArray.count)
        for _ in 0..<numFollowers { //will iterate four times
            let count = myKeyArray.count //get the number of elements
            let randomInt = Int.random(in: 0..<count) //get a random index for the array
            let randomUserKey = myKeyArray[randomInt]
            randomKeyArray.append(randomUserKey)
            myKeyArray.remove(at: randomInt) //remove that object so it's not selected again
        }

        let numberOfKeys = randomKeyArray.count

        var namesRemaining = numberOfKeys

        for i in 0..<numberOfKeys {
            let thisUserKey = randomKeyArray[i]
            let userRef = self.ref.child("users").child(thisUserKey)
            userRef.observeSingleEvent(of: .value, with: { snapshot in
                let name = snapshot.childSnapshot(forPath: "fullname").value as! String
                let profileImageUrl = snapshot.childSnapshot(forPath: "profileImageUrl").value as! String

                print(name)
                print(profileImageUrl)
                namesRemaining -= 1
                self.names.append(name)
                self.namesWithUrl[name] = profileImageUrl


                self.currIds.append(thisUserKey)

                if numFollowers <= 3 {
                    self.optionA.setTitle("Follow\nat least\n4 friends!", for: .normal)
                    self.optionA.titleLabel?.textAlignment = .center
                    self.optionA.setTitleColor(UIColor.lightGray, for: .normal)
                    self.optionA.isEnabled = false
                    self.optionB.setTitle("Follow\nat least\n4 friends!", for: .normal)
                    self.optionB.titleLabel?.textAlignment = .center
                    self.optionB.setTitleColor(UIColor.lightGray, for: .normal)
                    self.optionB.isEnabled = false
                    self.optionC.setTitle("Follow\nat least\n4 friends!", for: .normal)
                    self.optionC.titleLabel?.textAlignment = .center
                    self.optionC.setTitleColor(UIColor.lightGray, for: .normal)
                    self.optionC.isEnabled = false
                    self.optionD.setTitle("Follow\nat least\n4 friends!", for: .normal)
                    self.optionD.titleLabel?.textAlignment = .center
                    self.optionD.setTitleColor(UIColor.lightGray, for: .normal)
                    self.optionD.isEnabled = false
                }
                else if namesRemaining == 0 {
                    self.currNames = self.names
                    self.optionA.setTitle(self.names[0], for: .normal)
                    self.optionA.backgroundColor = UIColor.orange
                    self.imageViewA.sd_setImageLoad(URL(namesWithUrl[name[0]])) //this is where i am getting the error - here you want to set the image to the imageView not the scrollView

                    self.optionB.setTitle(self.names[1], for: .normal)
                    self.optionB.backgroundColor = UIColor.orange

                    self.optionC.setTitle(self.names[2], for: .normal)
                    self.optionC.backgroundColor = UIColor.orange
                    self.optionD.setTitle(self.names[3], for: .normal)
                    self.optionD.backgroundColor = UIColor.orange
                }
                self.userImageScrollView.contentSize = CGSize(width: (self.userImageScrollView.frame.size.width * CGFloat(self.namesWithUrl.count)), height: self.userImageScrollView.frame.size.height)
                self.userImageScrollView.delegate = self
            })
        }
    })
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    let pageNumber = userImageScrollView.contentOffset.x / userImageScrollView.frame.size.width
    imagePageControl.currentPage = Int(pageNumber)
}

更新:它的外观

图像现在看起来如何,而不是能够在它们之间滑动

编辑:试图做到这一点,以便您可以在图像之间滑动 - 但出现错误:应用程序委托上的线程 1 SIGBART

var frame = CGRect(x: 0, y: 0, width: 0, height: 0)

func setupLayout() {
    frame.origin.x = userImageScrollView.frame.size.width * CGFloat(4)
    frame.size = userImageScrollView.frame.size

    let imageViewA = UIImageView(frame: frame)
    userImageScrollView.addSubview(self.imageViewA)

    imageViewA.bottomAnchor.constraint(equalTo: userImageScrollView.bottomAnchor, constant: -5).isActive = true


    let imageViewB = UIImageView(frame: frame)
    userImageScrollView.addSubview(self.imageViewB)

    imageViewB.bottomAnchor.constraint(equalTo: userImageScrollView.bottomAnchor, constant: -5).isActive = true
    imageViewB.leftAnchor.constraint(equalTo: imageViewA.leftAnchor)

    let imageViewC = UIImageView(frame: frame)
    userImageScrollView.addSubview(imageViewC)

    imageViewC.bottomAnchor.constraint(equalTo: userImageScrollView.bottomAnchor, constant: -5).isActive = true
    imageViewC.leftAnchor.constraint(equalTo: imageViewB.leftAnchor)

    let imageViewD = UIImageView(frame: frame)
    userImageScrollView.addSubview(imageViewD)

    imageViewD.bottomAnchor.constraint(equalTo: userImageScrollView.bottomAnchor, constant: -5).isActive = true
    imageViewD.leftAnchor.constraint(equalTo: imageViewC.leftAnchor)

    self.userImageScrollView.contentSize = CGSize(width: (self.userImageScrollView.frame.size.width * CGFloat(4)), height: self.userImageScrollView.frame.size.height)
    self.userImageScrollView.delegate = self
}

标签: iosswiftfirebaseuiscrollview

解决方案


制作一本字典names:profileImageUrl

var namesWithUrl = [String : String]()

而不仅仅是names.append(name)这样做:

names.append(name)
namesWithUrl[name] = profileImageUrl

所以现在名称保存在具有正确 profileImageUrl 的字典中,因此字典将如下所示:

[name1value : name1URl, name2value : name2URl, ...]

然后,如果您使用SDWebImage,您可以非常简单地执行此操作:

self.optionA.setTitle(names, for: .normal)
self.optionA.backgroundColor = UIColor.orange
self.optionA.sd_setBackgroundImage(with: URL(namesWithUrl[name[1]]), for: .normal)
//If using the button image

self.optionB.setTitle(names[1], for: .normal)
self.optionB.backgroundColor = UIColor.orange
optionAImageView.sd_setImage(with: URL(namesWithUrl[name[1]]))
//if using a seperate imageView

这将很容易地将图像设置为您的 imageView,您只需在每一行下添加该行。

编辑:将图像视图添加到滚动视图。

您可以通过故事板将图像视图添加到滚动视图中,也可以像这样以编程方式添加它们:

首先声明它们:

var imageViewA = UIImageView()
var imageViewB = UIImageView()

然后我喜欢有一个 setupLayout 函数来处理我的视图:

func setupLayout() {

pinionImagesScrollView.addsubview(imageViewA)
imageViewA.translatesAutoResizingMaskIntoConstraints = false
imageViewA.widthAnchor.constraint(equalTo: pinionImagesScrollView.widthAnchor, constant: -10).isActive = true
imageViewA.heightAnchor.constraint(equalToConstant: 60).isActive = true
imageViewA.topAnchor.constraint(equalTo: pinionImagesScrollView.topAnchor, constant: -5).isActive = true

pinionImagesScrollView.addsubview(imageViewA)
imageViewB.translatesAutoResizingMaskIntoConstraints = false
imageViewB.widthAnchor.constraint(equalTo: pinionImagesScrollView.widthAnchor, constant: -10).isActive = true
imageViewB.heightAnchor.constraint(equalToConstant: 60).isActive = true
imageViewB.topAnchor.constraint(equalTo: imageViewA.bottomAnchor, constant: -5).isActive = true

}

在那里您可以看到我们如何将 imageViewB 放在 imageViewA 下方,并且宽度与滚动视图 -10 相同,从而提供了一些空间。

然后打电话setupLayout()进来viewDidLoad()。在您将图像放在它们上面之前,它们将是空的。和optionAImageView.sd_setImage(with: URL(namesWithUrl[name[1]]))

更新:

您可能需要将 URL 的字符串版本更改为 SD_setimage 的 URL,如下所示:

 let optionAUrl = URL.init(string: nameUrls[names[0]])
  imageView.sd_setImage(with: optionAUrl)

下标错误可能意味着您正在初始化字典错误,因为我已经测试过它应该可以正常工作。

更新:

setupLayout 的问题是您将自动布局与使用框架混合在一起。我假设你的 scrollViews 约束是在故事板中定义的,所以这是你将如何设置 imageViews,以便宽度和高度与 scrollView 相同,并且你可以在它们之间滚动。请注意,如果您想水平滚动,您应该研究使用 UICollectionView 代替。

在此示例中,我以编程方式创建滚动视图,您可以只关注图像视图,因为您的约束是在情节提要中制作的。

import UIKit

class ViewController: UIViewController {

let scrollView = UIScrollView()
let imageViewA = UIImageView()
let imageViewB = UIImageView()
let imageViewC = UIImageView()
//Declaring the imageViews

override func viewDidLoad() {
    super.viewDidLoad()

    setupLayout()
    // Do any additional setup after loading the view, typically from a nib.
}

func setupLayout() {
    view.addSubview(scrollView)
    scrollView.translatesAutoresizingMaskIntoConstraints = false
    scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    scrollView.bottomAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    scrollView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -10).isActive = true
    scrollView.backgroundColor = .gray
    //setting up the size of the scrollView

    scrollView.addSubview(imageViewA)
    //This means we are using autoLayout, building the views and setting their size based on how their constraints relate to other objects
    imageViewA.translatesAutoresizingMaskIntoConstraints = false
    imageViewA.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
    //Setting the imageViewA top anchor to the scrollView topanchor we are essentially saying the top of this imageView starts at the top of the scroll view
    imageViewA.widthAnchor.constraint(equalTo: scrollView.widthAnchor, constant: -10).isActive = true
    //Here the imageViews width is equal to the scrollViews width, (-10 is optional if you want it not to touch the edges)
    imageViewA.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor).isActive = true
     //CenterXAnchor here I am making sure the imageView is centered in the scrollView
    imageViewA.heightAnchor.constraint(equalTo: scrollView.heightAnchor, constant: -10).isActive = true
     //same with the height
    imageViewA.backgroundColor = .cyan
     //Background just for my testing as I dont have any images to sue
    imageViewA.contentMode = .scaleAspectFit
     //This is how you want the image to scale into the view for when you set it.
    scrollView.addSubview(imageViewB)
    imageViewB.translatesAutoresizingMaskIntoConstraints = false
    imageViewB.topAnchor.constraint(equalTo: imageViewA.bottomAnchor, constant: 10).isActive = true
    //Because we want to scroll down, the top anchor of imageViewB is equal to the bottom anchor of imageViewA meaning the top of B starts at the bottom of A
    imageViewB.heightAnchor.constraint(equalTo: scrollView.heightAnchor).isActive = true
   imageViewB.widthAnchor.constraint(equalTo: scrollView.widthAnchor, constant: -10).isActive = true
    //Height and widths are the same.
    imageViewB.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor).isActive = true
    imageViewB.backgroundColor = .cyan
    imageViewB.contentMode = scaleAspectFit
    scrollView.addSubview(imageViewC)
    imageViewC.translatesAutoresizingMaskIntoConstraints = false
    imageViewC.topAnchor.constraint(equalTo: imageViewB.bottomAnchor, constant: 10).isActive = true
    //imageViewCs top starts at bottom of B
    imageViewC.heightAnchor.constraint(equalTo: scrollView.heightAnchor).isActive = true
    imageViewC.widthAnchor.constraint(equalTo: scrollView.widthAnchor, constant: -10).isActive = true
    imageViewC.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor).isActive = true
    imageViewC.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
     //for the final view, it needs to be connected to the bottom so the scrollView is able to scroll.
    imageViewC.backgroundColor = .cyan
    imageViewC.contentMode = .scaleAspectFit
}


}

这给了我一个方形 Scrollview,它显示 imageViewA 并允许我向下滚动并查看 imageViewB,然后查看 imageView C

此代码的输出,scrollView 设置为视图的 centerYanchor,因此它停在中间,蓝色方块是 imageViews,image1 显示它是如何启动的,你可以看到 ImageViewA,然后 image2 显示你如何滚动到下一个图像:在此处输入图像描述

在此处输入图像描述


推荐阅读