簡體   English   中英

在 didSelectRowAtIndexPath 中更改自定義 UIImage

[英]Changing custom UIImage in didSelectRowAtIndexPath

我的單元格中有一個自定義UIImage ,當調用didSelectRowAtIndexPath時需要更改它。 出於某種原因,圖像沒有改變,我認為這是因為我在方法中聲明了單元格。

class CustomCell: UITableViewCell {

    @IBOutlet weak var indicator: UIImageView!

}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        var cell = tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as! CustomCell

        cell.indicator.image = UIImage(named: "newImage")

}

單擊單元格時,如何將UIImage更改為“newImage”?

從索引路徑創建單元格

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        var cell = tableView.cellForRowAtIndexPath(indexPath) as! CustomCell

        cell.indicator.image = UIImage(named: "newImage")

}

您需要創建一個 UIImage 變量並在按下 tableviewcell 時更改該圖像變量。

例如...

 var imageVar:UIImage = UIImage(named: "IM")

   func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell?

        let ImageView:UIImageView = cell!.viewWithTag(1) as! UIImageView

        ImageView.image = imageVar


}


    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

self.imageVar = UIImage(named: "Image")

self.tableView.reloadData

}

對於 Swift 5

   func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! MembersCell
        cell.member_status.image =  YourImage
}

另外,如果在表格視圖中的可重用單元格的情況下只想更改一個單元格圖像,而其他單元格圖像數據不受影響,類似於單選按鈕功能。 所以你可以實現如下:-

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let cell = tableView.cellForRow(at: indexPath) as? CustomCell {

            cell.indicator.image = UIImage(named: "newImage")
            
        }
    }
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        
        if let cell = tableView.cellForRow(at: indexPath) as? CustomCell {
       
            cell.indicator.image = UIImage(named: "oldImage")
        }
    }

然后輸出看起來像:-

在此處輸入圖片說明

而另一個:-

在此處輸入圖片說明

暫無
暫無

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

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