我正在制作一个应用程序,该应用程序在可效率的视图中具有每个行,并且该代码为如下。
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 95
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Int(numberOfButtonsNeeded!)!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "lightCell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! MyTableViewCell
cell.lightButton.addTarget(self, action: #selector(buttonPressed), for: .touchDown)
cell.lightButton?.tag = tags[indexPath.row]
return cell
}
本质上,我想要的是一个执行2个功能的按钮,我现在想跟踪按钮以及是否已按下按钮。
如果按下了按钮,我希望它显示一个称为" on.jpg"的图像并执行某个动作。如果未按下按钮,我希望它显示" off.jpg"并执行其他动作。
该按钮应在两个状态中的任何一个(按下或不按下)中,并且不应有中间状态。
我按下的按钮方法如下:
func buttonPressed(_ sender : UIButton){
if ("certain condition is met"){
guard let image = UIImage(named: "on.jpg") else {
print("Image Not Found")
return
}
sender.setImage(image, for: UIControlState.normal)
}
else if ("another condition is met"){
guard let image = UIImage(named: "off.jpg") else {
print("Image Not Found")
return
}
sender.setImage(image, for: UIControlState.normal)
}
}
我已经尝试使用分配给每个按钮的标签和变量尝试进行操作,但是它变得太复杂了,肯定有一种更简单的方法来保持跟踪。
最后,我将如何刷新桌面视图并确保所有状态始终同步
您必须在表数据源中添加一个布尔变量,并设置其默认值,该值是false的。按钮单击时,您可以像这样做代码
func buttonPressed(_ sender : UIButton){
let isPressed = dataSource[sender.tag].isButtonPressed
if isPressed {
/// Button Already Pressed
} else {
/// Button is not pressed
}
dataSource[sender.tag].isButtonPressed = !isPressed
}
此外,您的表代表保持不变。