簡體   English   中英

swift indexPath.row == 0對於UITableViewCell很奇怪

[英]swift indexPath.row==0 works weirdly for UITableViewCell

我正在嘗試制作一張桌子,其中第一個單元格的布局與其余單元格不同。 我想將圖像作為第一個單元格的背景,即它看起來像這樣:

在此處輸入圖片說明

這是我的實現代碼

 func imageCellAtIndexPath(indexPath:NSIndexPath) -> MainTableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier(imageCellIdentifier) as MainTableViewCell
    let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject

    let eTitle:NSString = object.valueForKey("title")!.description
    let deTitle  = eTitle.stringByDecodingHTMLEntities()
cell.artTitle.text = deTitle


    var full_url = object.valueForKey("thumbnailURL")!.description
    var url = NSURL(string: full_url)
    var image: UIImage?
    var request: NSURLRequest = NSURLRequest(URL: url!)
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in

        image = UIImage(data: data)
        if((indexPath.row)==0)  {
        var imageView = UIImageView(frame: CGRectMake(10, 10, cell.frame.width - 10, cell.frame.height - 10))
        imageView.image = image
       cell.backgroundView = UIView()
      cell.backgroundView?.addSubview(imageView)

        }
        else{
        cell.thumb.image = image
        }
    })

    return cell
}

bt問題是..當我向下滾動並再次向上滾動時,背景圖像開始重復,並且縮略圖也重疊,如下所示: 在此處輸入圖片說明

如果我再次上下滾動..這是發生了什么: 在此處輸入圖片說明

我可能做了一些愚蠢的錯誤bt m,無法弄清楚它是什么。 請幫助

問題是tableView出於效率目的正在重用該單元格,但從未對其進行重置。

如果單元格不在indexPath 0,則需要從背景視圖中清除/刪除imageView。

在表格視圖中,單元格被重用您應重置 單元格中 使用的單元格樣式的特定版本無關的部分。 就像是:

 if((indexPath.row)==0)  {
      let frame = CGRectMake(10, 10, 
                             cell.frame.width - 10, cell.frame.height - 10)
      var imageView = UIImageView(frame: frame)
      imageView.image = image
      cell.backgroundView = UIView()
      cell.backgroundView?.addSubview(imageView)

      // Reset 
      cell.thumb.image = nil
 } else{
      cell.thumb.image = image
      // Reset 
      cell.backgroundView = nil
 }

更好,更慣用的想法是針對這兩種單元格類型使用單獨的UITableViewCell設計,每種類型具有不同的重用標識符。 這樣,您無需擔心重置。

PS:您應該使用dequeueReusableCellWithIdentifier:forIndexPath:而不是較早的dequeueReusableCellWithIdentifier:因為它可以確保返回單元格。

也許您可以為此使用tableHeaderView 或者,如果您想要很多這樣的部分,則可以使用

func headerViewForSection(_ section: Int) -> UITableViewHeaderFooterView?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM