良好的联系人应用程序设计 - 自定义表格单元布局
问题描述:
注意:阅读完毕后,如果不恰当,请编辑标题。良好的联系人应用程序设计 - 自定义表格单元布局
我只是iOS的业余爱好者。我用自己的任务练习Objective-C,我试图创建一个没有任何后端的联系人应用程序。
问题:
在我的应用程序,我想在一个单元格中显示的名称和形象。我怎样才能做到这一点?我已经尝试添加到子视图中,将标签(对于名称)和图像视图(对于图像)添加到单元格。但是,它为每个不同的联系人类型提供了更多的条件检查。像...
//In cellForRowAtIndexPath,
UILabel *lblForCell=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
lblForCell.text=[arrForMyContacts objectAtIndex:indexPath.row];
[tblCellForContactTable.contentView addSubview:lblForCell];
if([lblForCell.text isEqual:@"Mom"]){
UIImageView *imgForContact=[[UIImageView alloc] initWithFrame:CGRectMake(200, 10, 60, 7)];
imgForContact.image=[UIImage imageNamed:@"Mom.png"];
[tblCellForContactTable.contentView addSubview: imgForContact];
}
//likewise condition increased for dad, bro etc...- bad design, Correct?
所以告诉我,它有任何其他方式来减少条件。
答
有几种方法可以做。首先创建一个Dictionary的数组。这样
NSMutableArray *contacts = [[NSMutableArray alloc] init];
NSDictionary *mom = [NSDictionary dictionaryWithObjectsAndKeys:@"MOM", @"Name",
@"mom.png", @"imageName",
nil];
NSDictionary *dad = [NSDictionary dictionaryWithObjectsAndKeys:@"DAD", @"Name",
@"dad.png", @"imageName",
nil];
NSDictionary *son = [NSDictionary dictionaryWithObjectsAndKeys:@"SON", @"Name",
@"son.png", @"imageName",
nil];
[contacts addObjectsFromArray:@[mom, dad, son]];
的第二个东西创建一个定制的UIView类,你可以使这个字典,init方法是这样的
-(id)initWithContactInfo:(NSDictionary *)contactInfo;
三处的tableView
//In cellForRowAtIndexPath,
NSDictionary *contact = [contacts objectAtIndex:indexpath.row];
MYCustomView *contactCell = [[MYCustomView alloc] initWithContactInfo:contact];
[cell.contentView addSubView:contactCell];
制作自定义视图为您提供了针对特定单元格自定义视图的灵活性。
我希望它有帮助。祝你好运
您可以使用开关条件,而不是多个条件.. – Manimaran
Objective-C中是否存在任何预定义数组,如多维数组?我除了那样,不仅有条件的陈述。 –