[英]Typecasting to UILabel in Objective-C
I have an NSArray
made of UILabel
s that I initialized with this statement (the actual pointer is created in the .h file): 我有一个用
UILabel
制成的NSArray
,我用此语句初始化了它(实际的指针在.h文件中创建):
interLabels = [NSArray arrayWithObjects:inter1,inter2,inter3, nil];
Later on I have an IBAction
method that responds and is supposed to update the array of labels when a button is clicked: 稍后,我有一个
IBAction
方法,该方法响应并应在单击按钮时更新标签数组:
-(IBAction)intervalButton:(id)sender{
int count = 0;
double val[3];
if(count < 3){
val[count] = number;
[interLabels objectAtIndex:count].text = [NSString stringWithFormat:@"%.2f", val[count]];
count++;
}
}
However, [interLabels objectAtIndex:count]
doesn't seem to be recognized as a UILabel
object, so I get a compiler error that states that the property "text" cannot be found on object type "id." 但是,
[interLabels objectAtIndex:count]
似乎没有被识别为UILabel
对象,因此出现编译器错误,指出无法在对象类型“ id”上找到属性“ text”。 How can I get the compiler to recognize this as a UILabel
? 如何使编译器将其识别为
UILabel
? Is this an issue that can be solved by typecasting? 这是可以通过类型转换解决的问题吗?
objectAtIndex returns you an reference of type 'id'. objectAtIndex返回类型为“ id”的引用。 You need to cast it to UILabel before the compiler / IDE will recognise the text property.
您需要先将其转换为UILabel,然后编译器/ IDE才能识别text属性。
Eg ((UILabel*) [interLabels objectAtIndex:count]).text = ... 例如((UILabel *)[interLabels objectAtIndex:count])。text = ...
Type id
does not need to be casted if you assign it to another variable. 如果将类型
id
分配给另一个变量,则无需强制转换。 And in your case i think it would be nicer since you actually do two things, first get a object from the array and then changes state on that object. 在您的情况下,我认为这样会更好,因为您实际上做了两件事,首先从数组中获取一个对象,然后更改该对象的状态。 Consider this.
考虑一下。
-(IBAction)intervalButton:(id)sender
{
for ( UILabel *label in interLabels )
{
label.text = [NSString stringWithFormat:@"%.2f", number];
}
}
I assumed you wanted a loop not a if statement since the if statement always evaluated to YES. 我假设您想要一个循环而不是一个if语句,因为if语句始终被评估为YES。 Also i assumed
number
is a instance variable in your class. 我也假设
number
是您课堂上的实例变量。
Actually when i looked at the code again you can probably remove most of it. 实际上,当我再次查看该代码时,您可能会删除其中的大部分代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.