关于UI通讯录

做了好几天的通讯录,微微有些心得,在这里希望能跟大家 分享一下,同时也加深自己的记忆。入过很多坑,所以经验应该对新手有所帮助。

首先我卡住的地方就是数据解析,一般数据都是字典套数组,数组里再套字典,这应该是最基础的数据解析了。但由于是新手所以还是绕了很久。

先说下思路,想要获取字典所有的联系人,首先必须要通过Key值(也就是联系人分组名)获得所有联系人的分组,然后再遍历这些分组,最后才能过去所有联系人。

//通过遍历的Key值获取每个联系人分组里所有的联系人并存入数组

//数据解析

- (void)analyData

{

NSString *path = [[NSBundle mainBundle]pathForResource:@"Contact" ofType:@"plist"];

self.ContactDic = [NSMutableDictionary dictionaryWithContentsOfFile:path];

self.keyArr = [NSMutableArray array];

self.keyArr = [[_ContactDic.allKeys sortedArrayUsingSelector:@selector(compare:)]mutableCopy];

self.modelArr = [NSMutableArray array];

for (NSString *key in _ContactDic) {

NSArray *array = _ContactDic[key];

for (NSDictionary *dic in array) {

Contact *model = [[Contact alloc]init];

[model setValuesForKeysWithDictionary:dic];

[_modelArr addObject:model];

}

}


然后第二个注意点就是利用model传值,我们都知道,从前往后传值一般使用属性,从后往前传值一般使用block或者代理,而model则可以用作传值的参数,但是赋值的时候需要特别注意,model存值得方式类似与字典,取值赋值都需要key和value来进行。赋值方法如下:

//通过属性赋值,将信息传到显示信息的界面

- (void)getMessage

{

self.NameLabel.text = [_contact valueForKey:@"name"];

self.SexLabel.text = [_contact valueForKey:@"sex"];

self.PhoneNumLabel.text = [_contact valueForKey:@"phoneNumber"];

self.IntroduceLabel.text = [_contact valueForKey:@"introduce"];

self.imageV.image = [UIImage imageNamed:[_contact valueForKey:@"photoName"]];

}//这里通过setValueForKey的方法来实现赋值。


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

//这里的_keyArr是我用来存储所有分组名的可变数组

//去model得

NSString *key = _keyArr[indexPath.section];

NSArray *array = _ContactDic[key];

Contact *model = array[indexPath.row];

TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell" forIndexPath:indexPath];

if (!cell) {

cell = [[TableViewCell alloc]initWithStyle:(UITableViewCellStyleValue2) reuseIdentifier:@"CustomCell"];

}

cell.model = model;

return cell;

}

这里的话一定要注意model的类型,不然创建出来的Cell是无法赋上值的.


//如果想要自定义cell的高度可以使用该方法

+ (CGFloat)getHeightWidthLab4:(NSString *)text

{

CGSize baseSize = CGSizeMake(KScreenW - 20, CGFLOAT_MAX);

NSDictionary *attrDic = @{NSFontAttributeName : [UIFont systemFontOfSize:17]};

CGRect rectToFit = [text boundingRectWithSize:baseSize options:(NSStringDrawingUsesLineFragmentOrigin) attributes:attrDic context:nil];

return rectToFit.size.height;

}

只需要在给Cell布局时将Cell的高度定义成这个返回值即可,然后在- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

这个方法中将返回值调用,就可以根据Label的高度来确定Cell的高度了

感觉这个方法不是太过重要,因为i之后StoryBoard中只需要写两个属性:self.tableView.rowHeight = UITableViewAutomaticDimension;

self.tableView.estimatedRowHeight = 10;

就可以实现自定义Cell了。

这只是通讯录的一小部分,新人会经常犯的错误,老司机就不用看了,太过于浅薄。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容