gpt4 book ai didi

ios - 使用 selectedBackgroundView 显示高亮状态

转载 作者:可可西里 更新时间:2023-11-01 00:53:30 26 4
gpt4 key购买 nike

想象一下您有一个 UICollectionView 的场景,并且您希望在每个单元格中有一个按钮填充整个单元格,以便您可以响应各种触摸事件来处理高亮外观。例如,当用户按下按钮时,您想要更改按钮的背景颜色,然后在他们拖出或取消触摸等时恢复它。现在想象一下这种情况,您不想更改按钮的背景颜色,而是要更改按钮的背景颜色单元格的 backgroundViewUIButton 没有背景 View ,只有 backgroundColorbackgroundImage

我有一个解决方案,但我想知道如果不推荐这种方法,它是否可以更清洁。触摸按钮后,我遍历它的 superview 直到我得到 UICollectionViewCell 然后我将它的 selected 属性设置为 true。在 cellForItemAtIndexPath 中,我根据需要设置了 selectedBackgroundView。这样得到了想要的行为,但是用selected state来表示highlight state,这样管理是不是不合适?什么会更好?

我可以在触摸按钮时获取 UICollectionViewCell 然后更改其 backgroundView 属性而不是在创建每个单元格时都这样做,这样就不需要更改 选择值。但这仍然不是一个很好的解决方案。

最佳答案

您不需要在 Collection View 单元格内设置一个按钮,只需在按下按钮时设置其突出显示颜色即可。只需将您的单元格的 selectedBackgroundView 设置为与您的单元格具有相同宽度和高度的 View ,并为该 View 提供您希望用来突出显示该单元格的 backgroundColor

我做的(肮脏的)实现是这样的:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CELL", forIndexPath: indexPath) as UICollectionViewCell
cell.selectedBackgroundView = {
let bgview = UIView(frame: CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height))
bgview.backgroundColor = UIColor.redColor()
return bgview
}()
return cell
}

然后,只需取消选择 didSelectItemAtIndexPath 中的单元格。 “按住”会自动为您处理,取消选择动画只会​​在用户抬起手指时触发。

我认为这很脏,因为每次单元格出列以便在 cellForItemAtIndexPath: 中重用时,您都在设置 selectedBackgroundView。我要做的是创建一个 UICollectionViewCell 子类,从那里设置它的 selectedBackgroundView,然后使用 registerNib: 注册该单元格registerClass: 在 Collection View 上。


添加:更清洁的版本。在您的自定义 Collection View 单元子类中,分配 backgroundViewselectedBackgroundView:

override init(frame: CGRect) {
super.init(frame: frame)

self.backgroundView = {
let view = UIView()
view.backgroundColor = UIColor.yellowColor()
return view
}()

self.selectedBackgroundView = {
let view = UIView()
view.backgroundColor = UIColor.redColor()
return view
}()
}

以及 View Controller 、 Collection View 数据源和委托(delegate)中的相关方法:

override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.registerClass(NSClassFromString("test.CustomCollectionViewCell"), forCellWithReuseIdentifier: "CELL")
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CELL", forIndexPath: indexPath) as UICollectionViewCell
return cell
}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
collectionView.deselectItemAtIndexPath(indexPath, animated: true)
}

关于ios - 使用 selectedBackgroundView 显示高亮状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27773119/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com