专业java、php、iOS、C++、网页设计、平面设计、网络营销、游戏开发、前端与移动开发培训机构
CollectionView选中设置
当
HMEmoticonToolbar
里面的按钮
选中时,HMEmoticonKeyboard
的代理方法:didSelectedButton:didSelectedType:
会被调用.根据选中不同的按钮让collectionView
滚动到对应的组// MARK: - 扩展 CZEmoticonKeyboard 实现 HMEmoticonToolbarDelegate extension HMEmoticonKeyboard: HMEmoticonToolbarDelegate { func didSelectedButton(didSelectedType type: HMEmoticonToolbarType) { print("选中了: \(type)") // 切换collectionView对应的section let indexPath = IndexPath(item: 0, section: type.rawValue) collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .left) } }
当
collectionView
滚动到某一页时,需要让对应的按钮选中。在HMEmoticonKeyboard
实现scrollViewDidScroll
代理方法,每当collectionView
滚动时都来判断该选中哪个按钮
extension HMEmoticonKeyboard: UICollectionViewDelegate { // 监听colletionView滚动,来动态设置toolBar上的按钮选中 func scrollViewDidScroll(_ scrollView: UIScrollView) { // 计算中心参照点 var refPoint = scrollView.center refPoint.x += scrollView.contentOffset.x // print("center: \(refPoint)") // 判断哪个cell包含这个参照点 for cell in collectionView.visibleCells { if cell.frame.contains(refPoint) { // 显示这个cell所在的组 let indexPath = collectionView.indexPath(for: cell) print("选中: \(indexPath?.section) 组") // 让toolBar选中按钮 toolBar.switchSelectedButton(withSection: indexPath!.section) break } } } }
HMEmoticonToolbar
实现switchSelectedButton:
方法,当别人调用时传入需要选中第几个按钮./** 切换选中按钮 parameter withSection: 当前collectionView选中的组 */ func switchSelectedButton(withSection section: Int) { // 获取当前要选中的按钮 let button = subviews[section] as! UIButton switchSelectedButton(button: button) }
HMEmoticonToolbar
默认选中最近
这组, 在HMEmoticonToolbar
里面实现awakeFromNib
方法,设置第0组
最近
按钮为选中状态override func awakeFromNib() { // 默认选中第0组 switchSelectedButton(withSection: 0) }