我会试着让我的尝试在写作上有意义。
我对tableview cell和uiswitch使用了代码而不是情节提要。单元格的数量基于计数。如何选择在不同单元格中的uiswitch的值发生更改时发生的情况。
我觉得我需要函数didselectrow,但我不知道如何访问它的uiswitch。正如您在handleswitchaction函数中看到的,每个uiswitch都执行该操作。
class SettingsCell: UITableViewCell {
lazy var switchControl: UISwitch = {
let switchControl = UISwitch()
switchControl.isOn = true
switchControl.onTintColor = UIColor(red: 55/255, green: 130/255, blue: 250/255, alpha: 1)
switchControl.translatesAutoresizingMaskIntoConstraints = false
switchControl.addTarget(self, action: #selector(handleSwitchAction), for: .valueChanged)
return switchControl
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(switchControl)
switchControl.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
switchControl.rightAnchor.constraint(equalTo: rightAnchor, constant: -12).isActive = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
//fatalError("init(coder:) has not been implemented")
}
@objc func handleSwitchAction(sender: UISwitch) {
if sender.isOn {
print("Is on")
} else {
print("Is off")
}
}
}发布于 2020-12-28 22:20:07
在dequeueReusableCell(withIdentifier:for:)中将标记添加到单元格
settingsCell.switchControl.tag = indexPath.row并在handleSwitchAction中将其用作
switch(sender.tag) {
case 0: // First row
case 1: // Second row
// ...
}标签属性在任何UIView中都可用:https://developer.apple.com/documentation/uikit/uiview/1622493-tag
发布于 2020-12-28 22:48:35
如果您的内容在以下位置的单元格中是静态的,则可以只切换不带标记的indexPath.row:
switch indexPath.row {
case 0:
...
}或者如果它是动态的,你需要从后端获取一些属性来知道如何处理。
https://stackoverflow.com/questions/65478978
复制相似问题