iOS Swift UITableView 和 UICollectionView 默认选中

只适用于单选情况

一. 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)
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值