iOS Swift表情选择器

3

最近我看到一个应用程序,它将表情符号选择器作为一种对某些事物做出反应的方式。我想将类似的概念实现到我的应用程序中,有人知道我如何创建像这张照片一样的东西吗?我想使用CollectionView,并使每个单元格成为自己的表情符号。有什么想法或更好的方法吗?

enter image description here


https://github.com/FarisAlbalawi/FAStickers - Faris
1个回答

10
将表情符号放入集合视图中,可以这样做:
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...在其他Stack Overflow帖子中也有其他答案。 - Ali
1
在Swift 5中,只需将“NSAttributedStringKey”引用更改为“NSAttributedString.Key”,即可消除未解决标识符的错误。 - Peter Brockmann

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接