Check if there is an emoji contained in a string

后端 未结 11 1110
野的像风
野的像风 2020-12-31 11:49

I am getting the text size of a string with this

textSize = [[tempDict valueForKeyPath:@\"caption.text\"] sizeWithFont:[UIFont systemFontOfSize:12] constrain         


        
11条回答
  •  被撕碎了的回忆
    2020-12-31 12:12

    Simple Swift solution with checking every scalar in unicodeScalars are in the set CharacterSet.symbols

    extension String {
        var containsEmoji: Bool {
            for scalar in unicodeScalars {
                if CharacterSet.symbols.contains(scalar) {
                    return true
                }
            }
    
            return false
        }
    }
    

    But I found some emoji 1.0 items like ℹ️ is not classify as an emoji. So I create this checker:

    extension Unicode.Scalar {
        extension Unicode.Scalar {
            var isEmojiMiscSymbol: Bool {
                switch self.value {
                case 0x2030...0x329F:   // Misc symbols
                    return true
                default:
                    return false
                }
            }
        }
    }
    

    And this is the checker which can detect ℹ️:

    extension String {
        var containsEmoji: Bool {
            for scalar in unicodeScalars {
                if CharacterSet.symbols.contains(scalar) {
                    return true
                } else if scalar.isEmojiMiscSymbol {
                    return true
                }
            }
    
            return false
        }
    }
    

提交回复
热议问题