-4
我最近看到一個應用程序,它包含了一個表情符號選擇器,用於對某些事情做出反應。我想實現一個類似的概念到我的應用程序,任何人都知道我可以創建像這張照片。我正在考慮使用collectionview,並讓每個單元格都是自己的表情符號。任何想法或更好的方法?Emoji Picker Ios Swift
我最近看到一個應用程序,它包含了一個表情符號選擇器,用於對某些事情做出反應。我想實現一個類似的概念到我的應用程序,任何人都知道我可以創建像這張照片。我正在考慮使用collectionview,並讓每個單元格都是自己的表情符號。任何想法或更好的方法?Emoji Picker Ios Swift
爲了把表情符號,爲的CollectionView,做這樣的:
var emojiList: [[String]] = []
let sectionTitle: [String] = ["Emoticons", "Dingbats", "Transport and map symbols", "Enclosed Characters"]
override func layoutSubviews() {
super.layoutSubviews()
fetchEmojis()
}
func fetchEmojis(){
let emojiRanges = [
0x1F601...0x1F64F,
0x2702...0x27B0,
0x1F680...0x1F6C0,
0x1F170...0x1F251
]
for range in emojiRanges {
var array: [String] = []
for i in range {
if let unicodeScalar = UnicodeScalar(i){
array.append(String(describing: unicodeScalar))
}
}
emojiList.append(array)
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! DragCell
cell.imageView.image = emojiList[indexPath.section][indexPath.item].image()
return cell
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return emojiList[section].count
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return emojiList.count
}
有了這個擴展:
extension String {
func image() -> UIImage? {
let size = CGSize(width: 100, height: 100)
UIGraphicsBeginImageContextWithOptions(size, false, 0);
UIColor.clear.set()
let stringBounds = (self as NSString).size(withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 75)])
let originX = (size.width - stringBounds.width)/2
let originY = (size.height - stringBounds.height)/2
print(stringBounds)
let rect = CGRect(origin: CGPoint(x: originX, y: originY), size: size)
UIRectFill(rect)
(self as NSString).draw(in: rect, withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 75)])
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
} 請記住,Unicode的表情符範圍可能不包括所有的表情符號,你可能想要查找和修改你的應用程序的範圍
我得到的NSAttributedStringKey的未解析的標識符的錯誤 – user6520705
我的答案在swift 4中有效......其他堆棧溢出帖子上還有其他答案 – Ali