ios - 为什么使用 viewWithTag 高效?

标签 ios objective-c

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;

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

最佳答案

我不同意答案。我认为使用标签通常不是一个好习惯,就您而言,这只是懒惰。您应该创建一个 UITableViewCell子类,标签作为属性。
迈克·凯勒 wrote a post about it :

Let’s assume you aren’t trying to store data in a view’s tag. Instead, you just want a quick and dirty way to grab a reference to a view. Is it OK to use tags in these situations?

Well, in almost every case I can think of, it is better to store a reference to the view using a real property somewhere, whether that’s an IBOutlet or just a regular property on your class.

Do you need to add some custom views to a UITableViewCell? Subclass it and add real properties. (...)

By using real properties you get stronger typing, better naming, better visibility of the moving parts of your app, and you don’t have to down-cast viewWithTag’s UIView* return type. You also get better performance because viewWithTag: must traverse the view hierarchy for every call.

To me, using tags seems to be another pattern driven purely by laziness.

关于ios - 为什么使用 viewWithTag 高效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17845896/

相关文章:

ios - 钥匙串(keychain)和 NSUserDefault 之间的区别?

ios - 我的手势识别器附加到错误的 View

iphone - 覆盖 openURL 后无法推送 View Controller

objective-c - iPhone 应用程序的设置包

objective-c - 指向 struct C/ObjC 中指针的指针

objective-c - 检查 float 的长度

ios - 如何在 iOS 中使用套接字连接从服务器获取响应?

ios - 具有 UITapGestureRecognizer 的 View 中的 UIButton

ios - 按变量对自定义对象数组进行排序

iphone - 语义问题 : Incompatible pointer to integer conversion sending 'NSUInteger *' (aka 'unsigned int *' ) to parameter of type 'NSUInteger'