【问题标题】:How to change the function a UISwitch does based on which cell that UISwitch is in如何根据 UISwitch 所在的单元格更改 UISwitch 的功能
【发布时间】:2021-04-05 07:19:56
【问题描述】:

我将尝试使我的尝试在写作中有意义。

我为 tableview 单元格和 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")
        }
    }

}

【问题讨论】:

标签: ios swift uitableview uiswitch


【解决方案1】:

在您的dequeueReusableCell(withIdentifier:for:) 中为您的单元格添加标签

settingsCell.switchControl.tag = indexPath.row

并在handleSwitchAction as 中使用它

switch(sender.tag) {
case 0: // First row
case 1: // Second row
// ...
}

Tag 属性在任何 UIView 中都可用:https://developer.apple.com/documentation/uikit/uiview/1622493-tag

【讨论】:

  • 嘿迪玛,感谢您的帮助。这对我帮助很大。
【解决方案2】:

如果您的内容是静态的,您可以只切换 indexPath.row 而不使用标签 在行的单元格中:

switch indexPath.row {
   case 0:
   ...
}

或者如果它是动态的,您需要从后端获取一些属性才能知道如何处理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    • 2011-04-08
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多