1 + (NSString *)transform:(NSString *)chinese 2 { 3 NSMutableString *pinyin = [chinese mutableCopy]; 4 CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO); 5 CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO); 6 NSLog(@"%@", pinyin); 7 return [pinyin uppercaseString]; 8 }
用kCFStringTransformMandarinLatin
方法轉化出來的是帶音標的拼音,如果需要去掉音標,則繼續使用kCFStringTransformStripCombiningMarks
方法即可。
但是這種方式性能可能會比較差。推薦使用第三方的使用 -------------->>試試這個第三方:https://github.com/kimziv/PinYin4Objc,支持多音字
下面自己做小Demo,可以 參考下面代碼
NSString *sourceText=@"我愛中文"; HanyuPinyinOutputFormat *outputFormat=[[HanyuPinyinOutputFormat alloc] init]; [outputFormat setToneType:ToneTypeWithoutTone]; [outputFormat setVCharType:VCharTypeWithV]; [outputFormat setCaseType:CaseTypeLowercase]; [PinyinHelper toHanyuPinyinStringWithNSString:sourceText withHanyuPinyinOutputFormat:outputFormat withNSString:@" " outputBlock:^(NSString *pinYin) { _outputTv.text=pinYin; //update ui }];