
Switch组件频繁使用于用户设置、自定义等场景,当Switch组件只有一个时,它的数据绑定、函数绑定和状态切换都相对简单,只需要对一个Switch进行操作即可。
但是,当我们在TableView和CollectionView中复用多个Switch时,就需要一个更好的方式去同时实现多个数据绑定、函数绑定和状态切换。
在这里先说明一下:
数据绑定是指需要判断当前Switch的初始值状态; 函数绑定是指点击不同的Switch执行不同的函数; 状态切换是指点击之后我们需要改变Switch的状态;
下面以CollectionView中使用多个Switch为例,进行实践演练。
Switch组件 创建Switch组件,设置identify为CellSwitch
Switch 通过在cellForItemAt中设置Switch的不同tag值,来区分Switch 这里我以
cell.CellSwitch.tag = indexPath.row
Switch初始化状态加载 在cellForItemAt中加载Switch的各种颜色和当前状态。 当然要明确不同的indexPath.row对应什么值,对应的Switch加载不同的初始状态,以OneClock自定义设置中的三个值为例,我调用coredata的值进行了初始化状态的加载。
switch indexPath.row {
case 0:
print("indexpath",indexPath.row)
if self.appDelegate.mytheme.timeFormat == Int64(0){
cell.CellSwitch.isOn = true
}else{
cell.CellSwitch.isOn = false
}
case 1:
print("indexpath",indexPath.row)
if self.appDelegate.mytheme.showFormat == Int64(0){
cell.CellSwitch.isOn = true
}else{
cell.CellSwitch.isOn = false
}
case 2:
print("indexpath",indexPath.row)
if self.appDelegate.mytheme.oneClickMenu == Int64(0){
cell.CellSwitch.isOn = true
}else{
cell.CellSwitch.isOn = false
}
default:
print("default")
}
Switch函数绑定 同样在cellForItemAt中加载Switch的函数self.switchAction(_ :),代码如下:
cell.CellSwitch.addTarget(self, action: #selector(self.switchAction(_ :)), for: .touchUpInside)当然,这里的核心是
self.switchAction(_ :)
函数本身,
刚刚我们已经给每个Switch加了tag,因此在这个函数中,我们就只需要判断tag值进行不同的函数操作即可。
@objc func switchAction(_ sender: UISwitch){
switch sender.tag {
case 0:
print("indexpath",sender.tag)
if self.appDelegate.mytheme.timeFormat == Int64(0){
self.appDelegate.mytheme.timeFormat = Int64(1)
}else{
self.appDelegate.mytheme.timeFormat = Int64(0)
}
case 1:
print("indexpath",sender.tag)
if self.appDelegate.mytheme.showFormat == Int64(0){
self.appDelegate.mytheme.showFormat = Int64(1)
}else{
self.appDelegate.mytheme.showFormat = Int64(0)
}
case 2:
print("indexpath",sender.tag)
if self.appDelegate.mytheme.oneClickMenu == Int64(0){
self.appDelegate.mytheme.oneClickMenu = Int64(1)
}else{
self.appDelegate.mytheme.oneClickMenu = Int64(0)
}
default:
print("default")
}
}
Switch状态 只要初始状态和函数改变的方式统一,每次点击都能获得正确的状态和值的改变,也可以在每次执行self.switchAction(_ :)时,加入整个CollectionView的重置:
self.CustomCollection.reload()
GitHub:OneSwift - iOS Tips Based On Swift
微博:xDEHANG