在异步调用中将数组索引到数组中Swift

在异步调用中将数组索引到数组中Swift

问题描述:

我试图创建一个“匹配”对象图像的滚动视图,它与我的视图控制器中的“匹配”对象数组相关联,以便如果我点击图像scrollView中的“匹配”,我可以在我的miniMatchesContainer中获取该图像的索引,并使用它访问该图像对应的数组中的Match对象。我试图用for循环来解决这个问题,但问题是,因为我从服务器异步获取匹配图像,调用返回的顺序不正确,所以我的containerView索引关闭(我添加了我的图像控制台的打印状态员显示我的意思)。所以现在我陷入了一个僵局,并希望得到一些有关从这里走向何处的建议。我应该改变我的方法吗?有什么我失踪?下面添加代码。在异步调用中将数组索引到数组中Swift

//function to create contentScrollView for MiniMyatches 
func setupMiniContentScroll(contentScroll: UIScrollView) { 
    let scalar:Double = 4/19 
    let contentViewDimension = contentScroll.frame.width * CGFloat(scalar) 
    let contentScrollWidth = CGFloat(LocalUser.matches.count) * (contentViewDimension + CGFloat(12)) - CGFloat(12) 
    let matchManager = MatchesManager() 

    for index in 0..<LocalUser.matches.count { 
     let match = LocalUser.matches[index] 
     print("Match index: \(index), Match at Index: \(match.itemName)") 
     matchManager.retrieveMatchThumbnail(match) { img, error in 

      if let img = img { 

       //create the mini matches views 
       let xOrigin = index == 0 ? 12 : CGFloat(index) * contentViewDimension + (CGFloat(12) * CGFloat(index) + CGFloat(12)) 
       let contentFrame = CGRectMake(xOrigin, 10, contentViewDimension, contentViewDimension) 
       let contentView = self.makeMiniContentView(contentFrame, image: img, matchedPrice: match.matchedPrice) 

       let tap = UITapGestureRecognizer(target: self, action: #selector(BrowseViewController.toggleItemInfo(_:))) 
       contentView.addGestureRecognizer(tap) 
       self.miniMatchContainer.append(contentView) 
       print("MiniMatchContainer Index: \(self.miniMatchContainer.indexOf(contentView)), Match at Index: \(match.itemName)") 

       //update the contentScrollView 
       dispatch_async(dispatch_get_main_queue()) { 

        let contentLabelFrame = CGRect(x: xOrigin, y: contentFrame.height + 15, width: contentFrame.width, height: 20) 
        let contentLabel = self.makeMiniContentLabel(contentLabelFrame, itemName: match.itemName) 
        let priceLabel = self.makeMiniPriceLabel(contentFrame, matchedPrice: match.matchedPrice) 

        contentScroll.addSubview(contentView) 
        contentScroll.addSubview(contentLabel) 
        contentScroll.addSubview(priceLabel) 
        contentScroll.contentSize = CGSizeMake(contentScrollWidth + CGFloat(16), contentScroll.frame.height) 
       } 
      } 

     } 
    } 
} 

enter image description here

我会尝试:

print("MiniMatchContainer Index: \(index), Match at Index: \(match.itemName)") 

相反的:

print("MiniMatchContainer Index: \(self.miniMatchContainer.indexOf(contentView)), Match at Index: \(match.itemName)") 

而且我会创建的内容提出看法retrieveMatchThumbnail,里面更新它。