为什么使用viewWithTag是有效的?

Lou*_*ost 1 objective-c ios

static NSString *cellID = @"Cell Identifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

if (!cell)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    [cell.contentView setBackgroundColor: [UIColor clearColor]];

    UIImage * box = [UIImage imageNamed: @"box.png"];
    UIView * cellbackgroundview = [[UIView alloc] initWithFrame: CGRectMake(7, 0, box.size.width, box.size.height)];
    [cellbackgroundview setBackgroundColor: [UIColor colorWithPatternImage: box]];

    UILabel * nameLabel = [[UILabel alloc] initWithFrame: CGRectMake( 0, 15, box.size.width, 19.0f)];
    nameLabel.text = name;
    [nameLabel setTextColor: [UIColor colorWithRed: 79.0f/255.0f green:79.0f/255.0f blue:79.0f/255.0f alpha:1.0f]];
    [nameLabel setFont: [UIFont fontWithName: @"HelveticaNeue-Bold" size: 18.0f]];
    [nameLabel setBackgroundColor: [UIColor clearColor]];
    nameLabel.textAlignment = NSTextAlignmentCenter;
    nameLabel.tag = 1;
    .....

}

((UILabel *)[cell viewWithTag:1]).text = name;
((UILabel *)[cell viewWithTag:2]).text = pitch;
Run Code Online (Sandbox Code Playgroud)

为什么像我上面那样使用viewWithTag是有效的?

Mar*_*bri 11

我不同意答案.我认为使用标签通常不是一个好习惯,在你的情况下,它只是懒惰.您应该创建一个UITableViewCell子类,标签作为属性.

迈克凯勒写了一篇关于它的帖子:

假设您没有尝试将数据存储在视图的标记中.相反,您只需要快速而肮脏的方式来获取对视图的引用.在这些情况下使用标签是否可以?

好吧,在我能想到的几乎所有情况下,最好使用某个地方的真实属性来存储对视图的引用,无论是IBOutlet还是类上的常规属性.

您是否需要向UITableViewCell添加一些自定义视图?对它进行子类化并添加实际属性.(......)

通过使用真实属性,您可以获得更强的输入,更好的命名,更好的应用程序移动部分的可见性,并且您不必向下转换viewWithTag的UIView*返回类型.您也可以获得更好的性能,因为viewWithTag:必须遍历每个调用的视图层次结构.

对我来说,使用标签似乎是纯粹由懒惰驱动的另一种模式.


Wai*_*ain 8

谁说它有效率?在什么情况下?

它不是真正有效,因为它执行视图层次结构的搜索以查找视图.有效的选择是创建一个单元子类,该子类具有您要访问的视图的属性,然后您可以在不进行任何搜索的情况下获取引用.