UITableViewCell使用Switch
Accessory
在系统默认的Cell中有一个叫做Accessory的视图,提供了两个可设置属性。
cell.accessoryType
cell.accessoryView
其中accessoryType需要一个枚举值,Table View Cell打勾等都是在设置设置的
cell.accessoryType = .disclosureIndicator
// 枚举值
.checkmark // 打勾
.disclosureIndicator // 箭头
.detailDisclosureButton
accessoryType也可以自定义颜色,其颜色跟随Cell
cell.tintColor = UIColor.systemBlue // 设置此颜色会影响Cell其他部分
但是accessoryType并没有Switch选项这时候就要用到accessoryView
accessoryView
accessoryView相比Type更加高级,因为他是一个独立的View,所以有很多玩法。
下面我们就来看看通过accessoryView给Table View Cell添加一个Switch。
创建Switch
accessoryView本身就是一个view,上面的所有控件都需要自己设置。
let swich = UISwitch() // 创建一个switch
swich.onTintColor = UIColor.systemBlue // 设置颜色
swich.addTarget(self, action: #selector(swichAction(_:)), for: .valueChanged) // 添加一个Target
swichAction(:)可以换成任何自定义函数
函数设计
@objc func swichAction(_ sender: UISwitch) {
if sender.isOn{
userDefaults.set(true, forKey: "isUserColor")
}else{
userDefaults.set(false, forKey: "isUserColor")
}
}
注意@objc一定要有,函数的入参是一个UISwicth,通过sender可以获得这个Switch的属性。
当然如果需要知道当前点击的是哪一个Switch就需要使用到superView
sender.superView
添加Switch
最后一步,将switch添加到accessoryView。
cell.accessoryView = swich