专业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 } } }
- 在
表情按钮
设置显示emoji
class 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
为nil
class HMEmoticonButton: UIButton { /// 表情模型 var emoticon: HMEmoticonModel? { didSet { if emoticon!.emoji != nil { // emoji 表情 self.setTitle(emoticon!.emoji!, for: .normal) } else { // 图片表情 // 清空文字 self.setTitle(nil, for: .normal) } } } }