仿照微信通讯录功能

作者: 孤独的剑客 | 来源:发表于2016-08-12 19:50 被阅读532次

最近工程中要做一个通讯录的功能,参考微信后发现微信的通讯录是将字符串全部转成拼音,然后进行排序。那么如何转成拼音呢然后排序?因为每个字符都有对应得编码,所以通过编码然后在转译就可以实现排序了。

先上个效果图

通讯录.gif

实现思路:

  • 取出系统A~#27个字符,将其加到索引的数组中
  • 创建一个数组,里面的元素为单个索引数量的数组
  • 判断名字在索引中的位置,添加到联系人(也就是索引数组中)
  • 索引数组排序
  • 去掉空的索引数组,只显示当前有的联系人

下面附上主要代码

  • 索引实现
    // 索引字体颜色
    _listTable.sectionIndexColor = [UIColor blueColor];
    // 索引点击后的背景颜色
    _listTable.sectionIndexTrackingBackgroundColor = [UIColor clearColor];
    // 索引的背景颜色
    _listTable.sectionIndexBackgroundColor = [UIColor clearColor];
    // 索引显示的内容
    -(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
    {
    return _titleArray;
    }
    // 索引点击滑动的联动
    -(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
    {
    return [_titleArray indexOfObject:title];
    }

  • 编码以对应的转译算法
    // 将中文转成拼音
    - (NSString *) pinyinFromChineseString:(NSString *)string {
    if(!string || ![string length]) return nil;
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding( kCFStringEncodingGB_18030_2000);
    NSData *gb2312_data = [string dataUsingEncoding:enc];

        unsigned char ucHigh, ucLow;
        int nCode;
        NSString *strValue = @"";
        int iLen = (int)[gb2312_data length];
        char *gb2312_string = (char *)[gb2312_data bytes];
        for (int i = 0; i < iLen; i++) {
            if ((unsigned char)gb2312_string[i] < 0x80 ) {
                strValue = [strValue stringByAppendingFormat:@"%c", gb2312_string[i] > 95 ? gb2312_string[i] - 32 : gb2312_string[i]];
                continue;
            }
      
            ucHigh = (unsigned char)gb2312_string[i];
            ucLow  = (unsigned char)gb2312_string[i + 1];
            if ( ucHigh < 0xa1 || ucLow < 0xa1)
                continue;
            else
                 nCode = (ucHigh - 0xa0) * 100 + ucLow - 0xa0;
                 NSString *strRes = FindLetter(nCode);
                 strValue = [strValue stringByAppendingString:strRes];
                 i++;
              }
        return [[NSString alloc] initWithString:strValue] ;
    }
    

最后附上代码[https://github.com/mrjiOS/ContactsDemo.git]

如果有其它的好的实现思路可以探讨下。

相关文章

网友评论

    本文标题:仿照微信通讯录功能

    本文链接:https://www.haomeiwen.com/subject/hwdesttx.html