首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何根据UISwitch所在的单元格更改UISwitch的功能

如何根据UISwitch所在的单元格更改UISwitch的功能
EN

Stack Overflow用户
提问于 2020-12-28 22:14:59
回答 2查看 31关注 0票数 2

我会试着让我的尝试在写作上有意义。

我对tableview cell和uiswitch使用了代码而不是情节提要。单元格的数量基于计数。如何选择在不同单元格中的uiswitch的值发生更改时发生的情况。

我觉得我需要函数didselectrow,但我不知道如何访问它的uiswitch。正如您在handleswitchaction函数中看到的,每个uiswitch都执行该操作。

代码语言:javascript
复制
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")
        }
    }

}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-12-28 22:20:07

dequeueReusableCell(withIdentifier:for:)中将标记添加到单元格

代码语言:javascript
复制
settingsCell.switchControl.tag = indexPath.row

并在handleSwitchAction中将其用作

代码语言:javascript
复制
switch(sender.tag) {
case 0: // First row
case 1: // Second row
// ...
}

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

票数 1
EN

Stack Overflow用户

发布于 2020-12-28 22:48:35

如果您的内容在以下位置的单元格中是静态的,则可以只切换不带标记的indexPath.row:

代码语言:javascript
复制
switch indexPath.row {
   case 0:
   ...
}

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65478978

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档