Jor*_*n H 2 uibutton ios uicollectionview uicollectionviewcell swift
想象一下这样的场景,UICollectionView在每个单元格中,您希望有一个按钮填充整个单元格,以便您可以响应各种触摸事件来处理高光外观。例如,当用户触摸按钮时,您想更改按钮的背景颜色,然后在拖出或取消触摸等时将其还原。现在想象一下您想要更改按钮的背景颜色而不是更改按钮的背景颜色的情况细胞的backgroundView. AUIButton没有背景视图,只有 abackgroundColor或backgroundImage。
我有一个解决方案,但我想知道它是否可以更清洁,如果不推荐这种方法。触摸按钮后,我会遍历它的superviews 直到得到 ,UICollectionViewCell然后将其selected属性设置为true。在cellForItemAtIndexPath我selectedBackgroundView根据需要设置。这样就得到了想要的行为,但是用selected状态来表示高亮状态,这样管理是不是不合适?什么会更好?
我可以UICollectionViewCell在触摸按钮后更改其backgroundView属性,而不是在创建每个单元格时执行此操作,然后就无需更改selected值。但这仍然不是一个很好的解决方案。
您不需要集合视图单元格内的按钮来设置它被按下时的突出显示颜色。只需将您的单元格设置为与您的单元格selectedBackgroundView具有相同宽度和高度的视图,并为该视图提供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
}
Run Code Online (Sandbox Code Playgroud)
然后,只需取消选择中的单元格didSelectItemAtIndexPath。“按住”会自动为你处理,取消选择动画只会在用户抬起手指时触发。
我认为这很脏,因为您selectedBackgroundView每次都在设置单元格出列以便在cellForItemAtIndexPath:. 我要做的是创建一个UICollectionViewCell子类,selectedBackgroundView从那里设置它,然后使用集合视图上的registerNib:或注册该单元格registerClass:。
添加:更清洁的版本。在您的自定义集合视图单元格子类中,分配backgroundView和selectedBackgroundView:
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
}()
}
Run Code Online (Sandbox Code Playgroud)
以及你的视图控件、集合视图数据源和委托中的相关方法:
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)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4002 次 |
| 最近记录: |