只适用于单选情况
一. UITableView
1.设置默认选中
// index 为默认选中的row
self.tableView.selectRow(at: IndexPath(row: index, section: 0), animated: false, scrollPosition: .none)
2. 设置选中状态并取消选中状态
在自定义cell 中重写 setSelected(_ selected: Bool, animated: Bool) 方法
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
self.setSelectStyle()
} else {
self.setDeSelectStyle()
}
}
private func setSelectStyle() {
titleLabel.textColor = UIColor.white
titleLabel.font = UIFont.systemFont(ofSize: 12, weight: .semibold)
contentView.backgroundColor = UIColor.blue
}
private func setDeSelectStyle() {
titleLabel.textColor = UIColor.black
titleLabel.font = UIFont.systemFont(ofSize: 12, weight: .medium)
contentView.backgroundColor = UIColor.white
}
二. UICollectionView
1.设置默认选中
// 在 reload 之后调用 selectItem
self.collectionView.reloadData()
self.collectionView.selectItem(at: IndexPath(row: self.selectedIndex, section: 0), animated: false, scrollPosition: .top)
2. 设置选中状态并取消选中状态
UICollectionViewCell 没有像 UITableViewCell的 setSelected(_ selected: Bool, animated: Bool) 方法, 但是有 isSelected 属性
在自定义cell 中重写 isSelected 属性, 新增自定义属性 isSelect 默认为 false
private var isSelect: Bool = false
override var isSelected: Bool {
set {
self.isSelect = newValue
if newValue {
self.setSelectedStyle()
} else {
self.setDeSelectedStyle()
}
}
get {
return self.isSelect
}
}
private func setSelectedStyle() {
titleLabel.backgroundColor = UIColor(hex: "#00F6FF")
titleLabel.textColor = .el_000823
titleLabel.font = UIFont.systemFont(ofSize: 13, weight: .semibold)
}
private func setDeSelectedStyle() {
titleLabel.backgroundColor = .el_EEEEEE
titleLabel.textColor = .el_666666
titleLabel.font = UIFont.systemFont(ofSize: 12)
}
网友评论