gpt4 book ai didi

ios - 通过函数初始化实例变量

转载 作者:行者123 更新时间:2023-12-01 18:18:45 25 4
gpt4 key购买 nike

我有一堆UILabel,需要全部设置相同,但框架不同。由于它们很多,因此我认为我可以通过编写一个函数来减少代码量:

-(void)addField:(UILabel *)label withFrame:(CGRect)frame toView:(id)view {
label = [[UILabel alloc] initWithFrame:frame];
label.layer.cornerRadius = 3;
[view addSubview:label];
}

并通过以下方式调用:
[self addField:fieldOneLabel withFrame:CGRectMake(20, 180, 61, 53) toView:theView];

这样做的目的是使字段正确显示,但对它进行调查并没有对fieldOneLabel进行初始化,因此它只是那里不再被引用的UILabel。我以为可能必须使用&,但我想我的理解是不正确的,因为它会导致编译器错误。我该怎么办?

最佳答案

您可能想返回标签,然后将其添加到UIView中,如下所示:

-(UILabel*)createLabelWithText:(NSString*)text andFrame:(CGRect)frame {
UILabel *label = [[UILabel alloc] initWithFrame:frame];
[label setText:text];
label.layer.cornerRadius = 3;
return label;
}

然后,在您的代码中可以执行以下操作:
UILabel *xLabel = [self createLabelWithText:@"Some Text" andFrame:CGRectMake(20, 180, 61, 53)];
[theView addSubview:xLabel];

或者,如果您想以后作为属性访问它:
self.xLabel = [self createLabelWithText:@"Some Text" andFrame:CGRectMake(20, 180, 61, 53)];
[theView addSubview:xLabel];

关于ios - 通过函数初始化实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18996095/

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