簡體   English   中英

Swift Tableview Cell單選按鈕實現

[英]Swift tableview cell radio button implementation

我需要在tableview自定義單元格中放置一個單選按鈕。 每當用戶單擊表格視圖單元格或按鈕時,單選按鈕都需要工作。 我嘗試使用下面的代碼,但執行效果不佳。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell:TableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! TableViewCell

        cell.country.text = self.animals[indexPath.row]

        cell.selectionStyle = UITableViewCellSelectionStyle.none;

        if selectedRows.contains(indexPath)
        {
            cell.radioButton.setImage(UIImage(named:"check.png"), for: .normal)
        }
        else
        {
            cell.radioButton.setImage(UIImage(named:"uncheck.png"), for: .normal)
        }

        return cell
    }

這是一個很棒的解決方案,它使用需要代碼的情節UITableViewUITableView創建單選按鈕-並具有2個很棒的酷提示!!

  • 確保將表視圖設置為“ 單選” ,並使用“ 靜態”單元格

  • 添加一個基本單元格,將圖像設置為未選中的按鈕圖像,並確保選擇樣式為默認

在此處輸入圖片說明

  • 酷提示#1:單擊並選擇單元格的圖像視圖,然后將其突出顯示的圖像設置為選中狀態。 突出顯示或選擇單元格后,其中的圖像視圖將更改以顯示其突出顯示的狀態。

在此處輸入圖片說明

  • 酷提示#2:接下來,將UIView拖到單元格的內容視圖中的文本標簽后面。 在使用基本單元格時,您將無法直接將其拖放到該單元格中,而需要將其拖動到左側的Document Outline中。 然后將其連接到單元格的選定背景視圖插座。 選擇一個單元格(或突出顯示一個單元格)時,此視圖將在后台顯示。 在這種情況下,我們將使用它來防止出現灰色背景,因此將其顏色設置為Clear 請注意,視圖的大小無關緊要,並且無需設置任何約束-它會在運行時自動調整大小以匹配單元格。

在此處輸入圖片說明

  • 最后,復制此單元格並更改每個單選按鈕選項的文本。 編譯並運行,您將獲得免代碼單選按鈕!

TableViewCell類中,為什么不創建數據源元素並覆蓋它的didSet 同樣在您的UITableView數據源中,我建議使用的數組不僅僅是String

我還沒有編譯下面的內容,所以這只是一個想法。

import UIKit

class TableViewCell : UITableViewCell {
    var data: Animal? {
        didSet {
            self.country.text = data.description
            if (data.isSelected) {
                self.radioButton.setImage(UIImage(named:"check.png"), for: .normal)
            } else {
                self.radioButton.setImage(UIImage(named:"uncheck.png"), for: .normal)
            }
        }
    }
}

當然,在視圖控制器中,每當點擊一行時,您都必須設置isSelected屬性。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    var animal = self.animals[indexPath.row]
    animal.isSelected = !animal.isSelected
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell:TableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! TableViewCell

    cell.data = self.animals[indexPath.row]
}

對於您的Animal可能是這樣的:

struct Animal {
    var description: String
    var isSelected: Bool
}

暫無
暫無

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

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