这是按钮操作的方法
@objc func recived()
{
kind = false
self.viewDidLoad()
self.viewWillAppear(true)
}
@objc func paid()
{
kind = true
self.viewDidLoad()
self.viewWillAppear(true)
}
这里是tableView的indexPath方法
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView .dequeueReusableCell(withIdentifier: "kindCell", for: indexPath) as! KindTableViewCell
if kind == true {
cell.recivedButton.addTarget(self, action:#selector (recived), for: UIControlEvents.touchUpInside)
cell.recivedButton.setImage(#imageLiteral(resourceName: "green on"), for: UIControlState.normal)
cell.paidButton.setImage(#imageLiteral(resourceName: "red off"), for: UIControlState.normal)
}
else{
cell.paidButton.addTarget(self, action: #selector (paid), for: UIControlEvents.touchUpInside)
cell.paidButton.setImage(#imageLiteral(resourceName: "red on"), for: UIControlState.normal)
cell.recivedButton.setImage(#imageLiteral(resourceName: "green off"), for: UIControlState.normal)
}
return cell
}
最佳答案
您应该在单元格本身中处理此逻辑。在 Interface Builder 中连接您的导出和操作,然后……
class KindTableViewCell: UITableViewCell {
@IBOutlet private weak var receivedButton: UIButton!
@IBOutlet private weak var paidButton: UIButton!
@IBAction func received(_ sender: UIButton) {
recivedButton.setImage(#imageLiteral(resourceName: "green on"), for: .normal)
paidButton.setImage(#imageLiteral(resourceName: "red off"), for: .normal)
}
@IBAction func paid(_ sender: UIButton) {
paidButton.setImage(#imageLiteral(resourceName: "red on"), for: .normal)
recivedButton.setImage(#imageLiteral(resourceName: "green off"), for: .normal)
}
}
注意按钮 socket 是如何私有(private)
的——这消除了在 View Controller 中更新它们的诱惑。让细胞更新自己的状态。
如果您需要在 View Controller 中做额外的工作,请将委托(delegate)协议(protocol)添加到您的 TableView 单元格中......
protocol KindTableViewCellDelegate: class {
func kindTableViewCellDidTapReceive(_ kindTableViewCell: KindTableViewCell)
func kindTableViewCellDidTapPaid(_ kindTableViewCell: KindTableViewCell)
}
class KindTableViewCell: UITableViewCell {
// Outlets
var delegate: KindTableViewCellDelegate?
@IBAction func received(_ sender: UIButton) {
// Update button state
delegate?.kindTableViewCellDidTapReceive(self)
}
@IBAction func paid(_ sender: UIButton) {
// Update button state
delegate?.kindTableViewCellDidTapPaid(self)
}
}
然后在你的 TableView Controller 中......
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView .dequeueReusableCell(withIdentifier: "kindCell", for: indexPath) as! KindTableViewCell
cell.delegate = self
return cell
}
关于ios - 如何在一个自定义 tableView 单元格中使用两个按钮?我想在单击一个按钮时更改它们的图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50315165/