我有一个单元格,它有一个自定义的UIView子类作为它的contentView子视图之一。该子类将用作标记列表。
在单元格创建方法中,我完成了对子类的以下调用:
- (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));这就是正在发生的事情:

同时,这也是我想要实现的:

发布于 2014-06-10 02:03:27
您正在使用(0,0)的框架原点初始化每个新创建的标签。这意味着您添加到categoriesView的每个标签都将被添加到另一个标签的顶部。每次添加新标签时,都需要将后续标签的x位置递增当前标签的width。
其次,由于-createLabelsForArray:是在-tableView:cellForRowAtIndexPath:中调用的,如果每次调用cellForRowAtIndexPath时searchResultsCell.categoriesView不是新视图,那么每次调用此方法时都会添加新的、重复的标签。您可能希望在再次添加标签之前检查标签是否已被添加,或者至少在添加新标签之前删除旧标签。
https://stackoverflow.com/questions/24125347
复制相似问题