[英]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
}
這是一個很棒的解決方案,它使用需要零代碼的情節UITableView
在UITableView
創建單選按鈕-並具有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.