专业java、php、iOS、C++、网页设计、平面设计、网络营销、游戏开发、前端与移动开发培训机构
显示emoji表情
在
HMEmoticonKeyboard的UICollectionViewDataSource方法里面返回对应的数据// 返回组数 func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { // 取得所有的表情包数量 return CZEmoticonManager.sharedInstance.packages.count } // 返回cell数量 func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // 取得对应的表情包页数 return CZEmoticonManager.sharedInstance.packages[section].pageEmoticons.count }- 在
HMEmoticonPageCell里面定义pageEmoticons属性,当cell要显示的时候给pageEmoticons赋值/// 每页要显示的emoticon表情模型 var pageEmoticons: [HMEmoticonModel]? 在
HMEmoticonKeyboard的cellForItemAtIndexPath方法设置每个cell的pageEmoticons属性// 返回cell func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! HMEmoticonPageCell cell.indexPath = indexPath cell.pageEmoticons = HMEmoticonManager.shared.packages[indexPath.section].pageEmoticons[indexPath.item] return cell }- 在
HMEmoticonPageCell的pageEmoticons来设置表情按钮显示emoji或图片表情- 自定义
HMEmoticonButton表情按钮,让表情按钮自己来确定显示内容class HMEmoticonButton: UIButton { /// 表情模型 var emoticon: HMEmoticonModel? } - 给表情按钮设置表情模型
/// 每页要显示的emoticon表情模型 var pageEmoticons: [HMEmoticonModel]? { didSet { // 遍历传入的每个模型,获取对应的按钮,将模型赋值给表情按钮 for (index, emoticon) in pageEmoticons!.enumerated() { // 获取每个模型 // 找到对应的按钮 let emoticonButton = emoticonButtons[index] emoticonButton.emoticon = emoticon } } } - 在
表情按钮设置显示emojiclass HMEmoticonButton: UIButton { /// 表情模型 var emoticon: HMEmoticonModel? { didSet { if emoticon!.code != nil { // emoji 表情 self.setTitle(emoticon!.code!, for: UIControlState.normal) } } } }
- 自定义
- 运行,发现显示的是
emoji对应的code. 
需要将
code转成emoji字符串,再显示出来.code转成emoji字符串由CZEmoticonModel模型来做/// emoji 16进制字符串 var code: String? { didSet { // 将 code 转成 emoji字符串 let scanner = Scanner(string: code!) var result: UInt32 = 0 scanner.scanHexInt32(&result) emoji = "\(Character(UnicodeScalar(result)!))" } } /// emoji字符串 var emoji: String?- 在
CZEmoticonButton的emoticon属性的didSet判断如果是emoji则显示emoji表情class HMEmoticonButton: UIButton { /// 表情模型 var emoticon: HMEmoticonModel? { didSet { if emoticon!.emoji != nil { // emoji 表情 self.setTitle(emoticon!.emoji!, for: UIControlState.normal) } } } } - 运行发现,由于
cell的复用, 不是emoji的按钮都显示了emoji, 需要判断当不是emoji时设置按钮的title为nilclass HMEmoticonButton: UIButton { /// 表情模型 var emoticon: HMEmoticonModel? { didSet { if emoticon!.emoji != nil { // emoji 表情 self.setTitle(emoticon!.emoji!, for: .normal) } else { // 图片表情 // 清空文字 self.setTitle(nil, for: .normal) } } } }