【发布时间】:2018-09-22 16:26:36
【问题描述】:
目前我正在尝试制作一个类似商店的视图,显示多个不同的列表(宇宙飞船),您一次只能选择一个。这将是一个游戏,您可以在其中选择不同的宇宙飞船。我正在用 UITableViewCell Xib 文件唱一个 UITableView。我只有一个表格单元格 Xib 文件来格式化所有不同的列表。选择按钮的样式应该类似于单选按钮。
我遇到的困难是,当我单击一个按钮时,它会使所有按钮都显示“已选中”。
这是我的代码:
TableViewController:
import UIKit
struct CellData {
var image: UIImage?
var message: String?
var id: Int?
}
var array = [String]()
var buttonArray = [ShopButton]()
class ViewController: UITableViewController {
var data = [CellData]()
override func viewDidLoad() {
super.viewDidLoad()
data = [CellData.init(image: #imageLiteral(resourceName: "ship_0"), message: "Red Ship", id: 0), CellData.init(image: #imageLiteral(resourceName: "ship_1"), message: "Blue Ship", id: 1), CellData.init(image: #imageLiteral(resourceName: "ship_3"), message: "Yellow Ship", id: 2)]
array = ["Select", "Select", "Select"]
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Bundle.main.loadNibNamed("TableViewCell", owner: self, options: nil)?.first as! TableViewCell
cell.mainImageView.image = data[indexPath.row].image
cell.mainLabel.text = data[indexPath.row].message
cell.buttonOutlet.setTitle(array[indexPath.row], for: .normal)
cell.buttonOutlet.tag = data[indexPath.row].id!
buttonArray.append(cell.buttonOutlet)
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150
}
}
TableViewCell
import UIKit
class TableViewCell: UITableViewCell {
@IBOutlet weak var mainImageView: UIImageView!
@IBOutlet weak var mainLabel: UILabel!
@IBOutlet weak var buttonOutlet: ShopButton!
@IBAction func button(_ sender: ShopButton) {
buttonOutlet.makeSelected()
}
override func awakeFromNib() {
super.awakeFromNib()
}
我的 UIButton 子类:
import UIKit
class ShopButton: UIButton {
var buttonID = Int()
func makeSelected() {
switch self.buttonID {
case 0:
array = ["Selected", "Select", "Select"]
buttonTitle()
print("Ship: Red Ship")
case 1:
array = ["Select", "Selected", "Select"]
buttonTitle()
print("Ship: Blue Ship")
case 2:
array = ["Select", "Select", "Selected"]
buttonTitle()
print("Ship: Yellow Ship")
default:
print("Error: Default Initiated")
}
}
func buttonTitle() {
for button:ShopButton in buttonArray {
button.setTitle(array[button.buttonID], for: .normal)
}
}
override func awakeFromNib() {
}
}
我意识到这可能不是进行此商店设置的最佳方法,因此,如果有人对如何解决此问题或比我目前所做的更好的其他方法有答案,我将不胜感激。谢谢。
【问题讨论】:
-
添加到目前为止您尝试过的代码。还要正确提及您的问题,例如您是否需要分别在每个单元格中实现单选按钮,或者您的表格视图单元格将作为一个选项使用
-
这个答案在
UITableViewstackoverflow.com/a/52401326/123632 中提供了无代码单选按钮
标签: ios swift uitableview cocoa-touch