做了好幾天的通訊錄,微微有些心得,在這里希望能跟大家 分享一下,同時(shí)也加深自己的記憶。入過很多坑,所以經(jīng)驗(yàn)應(yīng)該對(duì)新手有所幫助。
首先我卡住的地方就是數(shù)據(jù)解析,一般數(shù)據(jù)都是字典套數(shù)組,數(shù)組里再套字典,這應(yīng)該是最基礎(chǔ)的數(shù)據(jù)解析了。但由于是新手所以還是繞了很久。
先說下思路,想要獲取字典所有的聯(lián)系人,首先必須要通過Key值(也就是聯(lián)系人分組名)獲得所有聯(lián)系人的分組,然后再遍歷這些分組,最后才能過去所有聯(lián)系人。
//通過遍歷的Key值獲取每個(gè)聯(lián)系人分組里所有的聯(lián)系人并存入數(shù)組
//數(shù)據(jù)解析
- (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];
}
}
然后第二個(gè)注意點(diǎn)就是利用model傳值,我們都知道,從前往后傳值一般使用屬性,從后往前傳值一般使用block或者代理,而model則可以用作傳值的參數(shù),但是賦值的時(shí)候需要特別注意,model存值得方式類似與字典,取值賦值都需要key和value來進(jìn)行。賦值方法如下:
//通過屬性賦值,將信息傳到顯示信息的界面
- (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的方法來實(shí)現(xiàn)賦值。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//這里的_keyArr是我用來存儲(chǔ)所有分組名的可變數(shù)組
//去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的類型,不然創(chuàng)建出來的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布局時(shí)將Cell的高度定義成這個(gè)返回值即可,然后在- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
這個(gè)方法中將返回值調(diào)用,就可以根據(jù)Label的高度來確定Cell的高度了
感覺這個(gè)方法不是太過重要,因?yàn)閕之后StoryBoard中只需要寫兩個(gè)屬性:self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 10;
就可以實(shí)現(xiàn)自定義Cell了。
這只是通訊錄的一小部分,新人會(huì)經(jīng)常犯的錯(cuò)誤,老司機(jī)就不用看了,太過于淺薄。