gpt4 book ai didi

ios - 为什么使用 viewWithTag 高效?

转载 作者:行者123 更新时间:2023-12-01 17:13:17 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com