专业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
的layoutSubviews
override 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
里面添加调试label
class 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
为HMEmoticonPageCell
override func awakeFromNib() { super.awakeFromNib() collectionView.register(HMEmoticonPageCell.self, forCellWithReuseIdentifier: "cell") collectionView.dataSource = self // 设置toolBar代理 toolBar.delegate = self }
在
collectionView:cellForItemAt:
里面获取到HMEmoticonPageCell
,并设置indexPath
func 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 }
- 运行,效果如下