【问题标题】:How would I view the next image in an array of images?如何查看图像数组中的下一张图像?
【发布时间】:2017-11-04 07:00:24
【问题描述】:

在这个函数中,我需要改变图像视图的图像,将它移动到数组中的下一个图像上。

private func updateImage(index: Int) {
    for x in 0..<urlArray.count
    {
        let imageUrl:URL = URL(string: "\(urlArray.object(at: x) as! String)")!
        let request:URLRequest = URLRequest.init(url: imageUrl)
        NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main, completionHandler: { (response, imageDta, error) in
            if (error == nil)
            {
                self.imagesArray.add(UIImage(data: imageDta!)!)
                if self.imagesArray.count > 0
                {
                    self.iv.image = self.imagesArray.object(at: 0) as! UIImage
                }
            }else{
                print("ERROR - \(error!)")
            }
        })
    }

}

但是,目前,正在使用的图像被设置为我数组中索引 0 处的图像。如果多次调用此函数,我将如何移动到下一张图像?

这是我主要需要帮助的行:

self.iv.image = self.imagesArray.object(at: 0) as! UIImage

更新:我尝试将 Charly Pico 建议的代码添加到我的函数中,但它似乎并没有移动到数组中的下一个图像上,我认为这与它的调用方式有关。我将详细介绍我的文件是如何构建的,并希望能阐明我想如何使用更改图像代码。

var urlArray:NSMutableArray! = NSMutableArray()
var imagesArray:NSMutableArray! = NSMutableArray()

这些保存 URL 和图像的数组在任何函数之外。

func GetTheStories() {
    let ref = FIRDatabase.database().reference().child("Content")
    ref.observe(FIRDataEventType.value, with: {(snapshot) in
        self.fileArray.removeAll()
        if snapshot.childrenCount>0{
            for content in snapshot.children.allObjects as![FIRDataSnapshot]{
                let contentInfo = content.value as? [String: String]
                let contentType = contentInfo?["contentType"]
                let storyLink = contentInfo?["pathToImage"]
                let content = storyLink   
                self.urlArray = NSMutableArray.init(array:[storyLink])                    
            }   
        }  
    })
}

这是我调用的函数,用于将我的 Firebase 服务器中的 URL 附加到 URLSARRAY。

override func viewDidAppear(_ animated: Bool) {

    for x in 0..<urlArray.count
    {
        let imageUrl:URL = URL(string: "\(urlArray.object(at: x) as! String)")!
        let request:URLRequest = URLRequest.init(url: imageUrl)
        NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main, completionHandler: { (response, imageDta, error) in
            if (error == nil)
            {
                self.imagesArray.add(UIImage(data: imageDta!)!)
                if self.imagesArray.count > 0
                {
                    self.iv.image = self.imagesArray.object(at: 0) as! UIImage
                }
            }else{
                print("ERROR - \(error!)")
            }
        })
    }
}

这是 Charly 创建并解释的函数,它允许我在屏幕加载时在 ImageView 上设置初始图像

private func updateImage(index: Int) {
    var imageToPresent = 0
    for x in 0..<urlArray.count
    {
        let imageUrl:URL = URL(string: "\(urlArray.object(at: x) as! String)")!
        let request:URLRequest = URLRequest.init(url: imageUrl)
        NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main, completionHandler: { (response, imageDta, error) in
            if (error == nil)
            {
                self.imagesArray.removeAllObjects()
                self.imagesArray.add(UIImage(data: imageDta!)!)
                if self.imagesArray.count > 0
                {
                    for x in 0..<self.imagesArray.count
                    { 
                        if self.iv.image == self.imagesArray.object(at: x) as! UIImage
                        {
                            imageToPresent = x + 1 
                            if imageToPresent >= self.imagesArray.count
                            {   
                                imageToPresent = 0
                            }
                        }
                    }
                    self.iv.image = self.imagesArray.object(at: imageToPresent) as! UIImage
                }
            }else{
                print("ERROR - \(error!)")
            }
        })
    } 
}

这是被调用以将图像更新到数组中的下一个的函数。但是,我相信它也不起作用,因为我尝试在下面应用 Charly 的代码是不正确的。这个函数在 ViewDidLoad 中是这样调用的

updateImage(index: 0)

并在此处调用它来更新图像。当分段进度条变为下一个时调用此函数。

func segmentedProgressBarChangedIndex(index: Int) {
    print("Now showing index: \(index)")
    updateImage(index: index)
}

我知道为什么我不使用按钮和操作有点令人困惑,这主要是因为我正在尝试创建一个 Instagram 风格的故事,其中的片段在完成或点击屏幕时会改变图像到数组中的下一个。我知道有很多东西需要查看,但我认为这将解释我想如何更详细地使用图像数组。

【问题讨论】:

    标签: arrays swift xcode indexing


    【解决方案1】:

    所以,假设您的 imagesArray 包含 2 张图片,我建议您执行以下操作:

    //Create a @IBAction and attach it to a UIButton in your Storyboard as a touchUpInside action.
    @IBAction func changeImage()
    {
       //Set a variable with Int as 0.
       var imageToPresent = 0
    
       //Create a for to check image by image inside the array.
       for x in 0..<imagesArray.count
       {
    
          //Compare the image at self.iv with the image in imagesArray at index x. And if the images are the same add a + 1 to imageToPresent.
          if self.iv.image == imagesArray.object(at: x) as! UIImage
          {
             imageToPresent = x + 1
    
             //Check if imageToPresent isn't bigger or equal than imagesArray, otherwise we will get an error and the App will crash.
             if imageToPresent >= imagesArray.count
             {
    
                //If imageToPreset if bigger or equal to imagesArray.count, it means that there are no more images at a higher index, so we return imageToPresent to 0.
                imageToPresent = 0
             }
          }
       }
    
       //Set the new image of imagesArray at index imageToPresent as UIImage to self.iv.
       self.iv.image = imagesArray.object(at: imageToPresent) as! UIImage
    }
    

    每次您想更改self.iv image 时,您都需要触摸按钮以触发操作。

    更新

    所以我添加了一个 NSTimer 来模拟您的 Progress View 在 3 秒内完成动画,3 秒后它将图像旋转到另一个,您可以在 for 之后添加此代码,该代码从网址:

    Timer.scheduledTimer(withTimeInterval: 3.0, repeats: true) { (timer) in
            self.changeImage()
        }
    

    首先将您的 urlArray 更新为:

    urlArray = NSMutableArray.init(array: ["https://firebasestorage.googleapis.com/v0/b/motive-73352.appspot.com/o/Content%2F20170525130622.jpg?alt=media&token=1e654c60-2f47-43c3-9298-b0282d27f66c","https://www.videomaker.com/sites/videomaker.com/files/styles/magazine_article_primary/public/articles/18984/363%20C03%20Lighting%20primary.png"])
    

    所以你至少有 2 张图片来进行图片旋转。

    【讨论】:

    • 我明天试试这个,谢谢你的帮助!
    • 我已经尝试将此代码添加到 updateImage 函数,但它似乎并不完全有效。我将发布更新,更详细地显示代码的工作原理
    • 有什么建议吗?
    • 抱歉,有段时间没有回复,一直很忙。为什么要使用分段进度条?
    • 没问题,我正在尝试使用从我的数据库中提取的内容创建我自己的 Instagram 故事版本。主要是为了展示我最终想要实现的功能的原型
    【解决方案2】:

    更改行以使用像这样传递给您的函数的索引

    self.iv.image = self.imagesArray.object(at: index) as! UIImage
    

    【讨论】:

      【解决方案3】:

      这个函数试图一次做很多事情,所以很难说如何让它做你想做的事情,但是你确实有一个索引参数。在这里使用它而不是 0:

        if self.imagesArray.count > index
        {
              self.iv.image = self.imagesArray.object(at: index) as! UIImage
        }
      

      将等待该图像加载,然后将其设置为视图。

      注意:您需要检查索引是否在范围内

      【讨论】:

        猜你喜欢
        • 2018-01-17
        • 1970-01-01
        • 2018-09-17
        • 1970-01-01
        • 1970-01-01
        • 2013-09-04
        • 2020-07-11
        • 1970-01-01
        • 2014-12-15
        相关资源
        最近更新 更多