Ios 将字符串数组添加到单元格子视图中的标签
我有一个单元格,其中有一个自定义UIView子类作为其contentView子视图之一。子类将用作标记列表 在单元创建方法中,我完成了对子类的以下调用:Ios 将字符串数组添加到单元格子视图中的标签,ios,ios7,uitableview,uiview,uilabel,Ios,Ios7,Uitableview,Uiview,Uilabel,我有一个单元格,其中有一个自定义UIView子类作为其contentView子视图之一。子类将用作标记列表 在单元创建方法中,我完成了对子类的以下调用: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { [searchResultCell.categoriesView createLabelsForArray:newCats]; 它调用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
[searchResultCell.categoriesView createLabelsForArray:newCats];
它调用以下方法:
-(void)createLabelsForArray:(NSArray *)labelArray {
NSLog(@"%s",__PRETTY_FUNCTION__);
for (NSString *labelTextString in labelArray) {
NSLog(@"label string : %@",labelTextString);
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont systemFontOfSize:12], NSFontAttributeName,
nil];
CGRect frame = [labelTextString boundingRectWithSize:CGSizeMake(128, 15)
options:NSStringDrawingTruncatesLastVisibleLine
attributes:attributesDictionary
context:nil];
CGSize size = frame.size;
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, size.width, size.height)];
label.textColor = [UIColor blueColor];
label.text = labelTextString;
NSLog(@"label frame: %@",NSStringFromCGRect(label.frame));
[self addSubview:label];
}
NSLog(@"self frame: %@",NSStringFromCGRect(self.frame));
这就是正在发生的事情:
虽然这是我努力实现的目标:
您正在初始化每个新创建的标签,其框架原点为
(0,0)
。这意味着您添加到categoriesView的每个标签都将被添加到彼此的顶部。每次添加新标签时,都需要将后续标签的x
位置增加当前标签的宽度
其次,由于在-tableView:cellForRowAtIndexPath:
中调用了-createLabelsForArray:
,因此如果每次调用cellForRowAtIndexPath
时,只要调用此方法,就会添加新的重复标签。在再次添加标签之前,您可能需要检查标签是否已添加,或者至少在添加新标签之前删除旧标签。Hi@StuartM,您在记录单个标签框时会看到什么?你为什么把它们都放在{0,0}点上?谢谢,这很有道理。在for循环中存储宽度并重用的最佳方法是什么,对于我需要0,0的第一个对象,然后我需要为其他对象存储宽度?是否有一种简单的方法可以每次清理cellForRow…
中的支架视图?