【问题标题】:Trying to override "selected" in UICollectionViewCell Swift for custom selection state试图在 UICollectionViewCell Swift 中覆盖“selected”以实现自定义选择状态
【发布时间】:2015-07-09 23:21:24
【问题描述】:

我正在尝试为 UICollectionView 中的单元格实现自定义选择样式。尽管可以很容易地在 didSelect 和 didDeSelect 方法中手动执行此操作,但我想通过操作 UICollectionViewCell 中的“selected”变量来实现这一点。

我有这个代码:

    override var selected: Bool {
    get {
        return super.selected
    }
    set {
        if newValue {
            self.imageView.alpha = 0.5
            println("selected")
        } else if newValue == false {
            self.imageView.alpha = 1.0
            println("deselected")
        }
    }
}

现在,当我选择一个单元格时,该单元格会突出显示,但“选定”会打印两次,并且取消选择不起作用(即使实现了两个 UICollectionView 方法)。

我该怎么做呢?谢谢!

【问题讨论】:

  • 您是否尝试过设置断点并在第一个“选定”被击中时进行跟踪?
  • 谢谢。帮我解决了问题。 super.selected 未被修改

标签: ios swift uicollectionview uicollectionviewcell


【解决方案1】:

对于 Swift 3.0:

override var isSelected: Bool {
    didSet {
        alpha = isSelected ? 0.5 : 1.0
    }
}

【讨论】:

  • 应该选择这个作为答案,因为它对应于最新版本的iOS并且仅使用didSet
  • 滚动时为什么会调用isSelected?
【解决方案2】:

通过单步执行代码来解决这个问题。问题是 super.selected 没有被修改。所以我把代码改成这样:

override var selected: Bool {
    get {
        return super.selected
    }
    set {
        if newValue {
            super.selected = true
            self.imageView.alpha = 0.5
            println("selected")
        } else if newValue == false {
            super.selected = false
            self.imageView.alpha = 1.0
            println("deselected")
        }
    }
}

现在它正在工作。

【讨论】:

  • 很高兴它的工作!您应该能够很快将您的答案标记为正确
  • 太棒了..!!帮助(Y)并为回答自己的问题竖起大拇指
  • 可能会为 Swift 3 添加更新。selected 不是“isSelected”
【解决方案3】:

试试这个。

override var selected: Bool {
    didSet {
        self.alpha = self.selected ? 0.5 : 1.0
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 2019-05-30
    • 1970-01-01
    • 2016-04-04
    • 2017-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多