专业java、php、iOS、C++、网页设计、平面设计、网络营销、游戏开发、前端与移动开发培训机构
表情键盘设置CollectionView
设置
CollectionView- 在
HMEmoticonKeyboard.xib中设置CollectionView的布局参数 
在
HMEmoticonKeyboard的awakeFromNib方法中设置CollectionView的参数override func awakeFromNib() { super.awakeFromNib() // 注册Cell collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell") // 设置数据源 collectionView.dataSource = self // 设置toolBar代理 toolBar.delegate = self }扩展
CZEmoticonKeyboard实现CollectionView的数据源方法extension HMEmoticonKeyboard: HMEmoticonToolbarDelegate { func didSelectedButton(didSelectedType type: HMEmoticonToolbarType) { print("选中了: \(type)") } }extension HMEmoticonKeyboard: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return items.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items[section] } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) cell.backgroundColor = UIColor.random return cell } }覆盖
HMEmoticonKeyboard的layoutSubviewsoverride func layoutSubviews() { super.layoutSubviews() // 获取到collectionView的布局 let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout // 设置itemSize大小 layout.itemSize = collectionView!.frame.size }- 运行,效果如下

- 在
自定义
UICollectionViewCell自定义
HMEmoticonPageCell, 每个Cell表示一页,一页显示20个表情按钮和一个删除按钮class HMEmoticonPageCell: UICollectionViewCell { }在
HMEmoticonPageCell里面添加调试labelclass HMEmoticonPageCell: UICollectionViewCell { var indexPath: IndexPath? { didSet { messageLabel.text = "当前第\(indexPath!.section)组, 第\(indexPath!.item)页" } } override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { contentView.addSubview(messageLabel) } // MARK: - 懒加载 // 测试label private lazy var messageLabel: UILabel = UILabel(frame: CGRect(origin: CGPoint(), size: CGSize(width: 300, height: 200))) }在
HMEmoticonKeyboard修改CollectionView注册的Cell为HMEmoticonPageCelloverride func awakeFromNib() { super.awakeFromNib() collectionView.register(HMEmoticonPageCell.self, forCellWithReuseIdentifier: "cell") collectionView.dataSource = self // 设置toolBar代理 toolBar.delegate = self }在
collectionView:cellForItemAt:里面获取到HMEmoticonPageCell,并设置indexPathfunc collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! HMEmoticonPageCell cell.indexPath = indexPath cell.backgroundColor = UIColor.random return cell }- 运行,效果如下
