做了好幾天的通訊錄,微微有些心得,在這里希望能跟大家 分享一下,同時也加深自己的記憶。入過很多坑,所以經驗應該對新手有所幫助。
首先我卡住的地方就是數據解析,一般數據都是字典套數組,數組里再套字典,這應該是最基礎的數據解析了。但由于是新手所以還是繞了很久。
先說下思路,想要獲取字典所有的聯系人,首先必須要通過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的類型,不然創(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布局時將Cell的高度定義成這個返回值即可,然后在- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
這個方法中將返回值調用,就可以根據Label的高度來確定Cell的高度了
感覺這個方法不是太過重要,因為i之后StoryBoard中只需要寫兩個屬性:self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 10;
就可以實現自定義Cell了。
這只是通訊錄的一小部分,新人會經常犯的錯誤,老司機就不用看了,太過于淺薄。