xcode 在目标 c 中动态命名标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9597026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 23:32:59  来源:igfitidea点击:

Dynamically name labels in objective c

iosiphoneobjective-cxcode

提问by SNV7

I'm new to iOS development, just had a quick question. I'm creating an app with 100 UILabel's. Each label is numbered 0 to 99. The problem is that I dont want to do this for all 100 labels.

我是 iOS 开发的新手,只是有一个简单的问题。我正在创建一个包含 100 个 UILabel 的应用程序。每个标签编号为 0 到 99。问题是我不想对所有 100 个标签都这样做。

output1.text = [[NSString alloc] initWithFormat:@"1"];
output2.text = [[NSString alloc] initWithFormat:@"2"];
.....
output100.text = [[NSString alloc] initWithFormat:@"100"];

Instead I'd like to do this a little more dynamically. Below I'm trying to use loops to dynamically create a string. For example by appending "1.text" to the end of "output" I get the string "output1.text".

相反,我想更动态地执行此操作。下面我尝试使用循环来动态创建一个字符串。例如,通过将“1.text”附加到“output”的末尾,我得到字符串“output1.text”。

for (int i=0; i< 100; i++) {
    outputNameString = [NSMutableString stringWithCapacity:0];
    [outputNameString setString:@"output"];
    [outputNameString appendString:[NSString stringWithFormat:@"%i.text",i + 1]];
    outputNameString = [[NSString alloc] initWithFormat:@"%@",i];
}

"output1" to "output100" are properly declared in the interface section and synthesized properly. Is there something I'm missing here, or is this simply not possible? Any help would be appreciated.

“output1”到“output100”在接口部分正确声明并正确合成。我在这里遗漏了什么,或者这根本不可能?任何帮助,将不胜感激。

回答by Shubhank

when you create the label.. set them tags from lets say (100---200 )

当你创建标签时..从让他们说(100---200)设置标签

so . initialize your label like this..

所以 。像这样初始化你的标签..

 for (int i=0; i< 100; i++) {

UILabel *label = [[UILabel alloc] init] ;
// label formatting code here...

label.tag = i+100;
   }

then get your label like this..and set its text

然后像这样得到你的标签......并设置它的文本

for (int i=0; i< 100; i++) {

UILabel *myLabel = (UILabel *)[self.view viewWithTag:i+100]; // get the label with tag
myLabel.text = [NSString stringWithFormat:@" Label %d",i+1"];
}

this should work great.. What is the problem.?

这应该很好用..有什么问题。?

回答by nacho4d

Providing you have an array (NSArray) with all your labels, this is a solution:

如果您有一个NSArray包含所有标签的数组 ( ),这是一个解决方案:

for (int i=0; i< 100; i++) {
    UILabel *label = [arrayOfLabels objectAtIndex:i];
    label.text = [NSString stringWithFormat:@"output.%d.text", i+1];
}



Edit : Allocating, storing and accessing 100 objects

编辑:分配、存储和访问 100 个对象

I think is better to have all label pointers in an array rather than tagging them, specially because you have a hundred! and each time you call viewWithTag:method it searches the view, it's not indexed.

我认为最好将所有标签指针放在一个数组中而不是标记它们,特别是因为您有一百个!每次您调用viewWithTag:方法时,它都会搜索视图,但不会编入索引。

Using NSArray:

使用 NSArray:

@interface Object : SuperObject {
    NSArray *labels;
}
@end
@implementation
- (void)someMethodThatCreatesLabels {
    labels = [[NSMutableArray alloc] initWithCapacity:100];
    for(NSInteger i = 0; i < 100; i++){
        UILabel *label = [[UILabel alloc] ...];
        label.text = [NSString stringWithFormat:@"output.%d.text", i+1];
        [view addSubview:label]
        [labels addObject:label];
        [label release];
    }
}
- (void)methodThatAccessALabel{
    UILabel *label45 = [labels objectAtIndex:45];
    // Do your thing ...
}
- (void)dealloc{
    [labels release];
    [super dealloc];
}
@end

Using C arrays, which Is a bit shorter (labels[i]instead of [labels objectAtIndex:i])

使用 C 数组,它有点短(labels[i]而不是[labels objectAtIndex:i]

@interface Object : SuperObject {
    UILabel **labels;
}
@end
@implementation Object
- (void)methodThatCreatesLabels
{
    labels = malloc(100*sizeOf(UILabel *));
    for(NSInteger i = 0; i < 100; i++){
        labels[i] = [[UILabel alloc] ...];
        labels[i].text = [NSString stringWithFormat:@"output.%d.text", i+1];
        [view addSubview:labels[i]]
    }
}
- (void)methodThatAccessALabel{
    UILabel *label45 = labels[45];
    // Do your thing ...
}
- (void)dealloc{
    for(int i = 0; i<100; i++) [labels[i] release];
    free(labels);
    [super dealloc];
}

回答by EmilioPelaez

The way to get variables with "variable" names is arrays.

获取具有“变量”名称的变量的方法是数组。

You can do one of two:

您可以执行以下两种操作之一:

UILabel *output[100];
for(NSInteger i = 0; i < 100; i++){
  output[i] = [[UILabel alloc] ...];
}

This will declare an array of 100 labels, from 0 to 99, and you can access them like this:

这将声明一个包含 100 个标签的数组,从 0 到 99,您可以像这样访问它们:

[output[50] setText:text];

The other way is:

另一种方式是:

NSMutableArray *outputLabels = [[NSMutableArray alloc] initWithCapacity:100];
for(NSInteger i = 0; i < 100; i++){
  UILabel *label = [[UILabel alloc] ...];
  [outputLabels addObject:label];
}

And access them like this:

并像这样访问它们:

[[outputLabels objectAtIndex:50] setText:text];

In general, you should read about C arrays, and then read the documentation about NSArray and NSMutableArray.

通常,您应该阅读 C 数组,然后阅读有关 NSArray 和 NSMutableArray 的文档。

回答by Ravin

In iOS you can manage views by tagging them. So for your purpose you can create a base view, on this you will add all the labels with proper tags. Later on whenever you need particular label just query view with method viewWithTag.

在 iOS 中,您可以通过标记视图来管理视图。因此,出于您的目的,您可以创建一个基本视图,在此基础上您将添加带有适当标签的所有标签。稍后每当您需要特定标签时,只需使用方法查询视图即可viewWithTag

Here is how you can implement it:

以下是您可以如何实施它:

Creating labels:

创建标签:

UIView *baseView = [[UIView alloc] init];
//keep its reference for later use.. you will need to make it instance variable if you want to access labels in other than this method.

for(int i=0;i<100;i++)
{
   UILabel *label = [[UILabel alloc] init];
   label.tag = i+1; //we are offsetting its value by 1 because tag=0 is for the baseview itself.
   label.text = <the text you wish to assign>;
   [baseView addSubview:label];
   [label release]; //if you are not using ARC.
   label = nil;
}

Accessing labels:

访问标签:

UILabel *label = (UILabel *)[baseView viewWithTag:<provide the tag value you wish to access>];

For more information about UIView tagging you can refer documentation.

有关 UIView 标记的更多信息,您可以参考文档

回答by Swapnil Luktuke

When you say, 'Each label is numbered 0 to 99', you mean they have those tags right? If yes, start your tags from 1 to 100 not 0 to 99. If no, set tags for each label. (If you dont know what tags are, read about 'tag' property in UIView documentation)

当您说“每个标签的编号为 0 到 99”时,您的意思是他们有这些标签,对吗?如果是,从 1 到 100 开始你的标签,而不是 0 到 99。如果不是,为每个标签设置标签。(如果您不知道标签是什么,请阅读UIView 文档中的“标签”属性)

Then, you can easily access these labels in a loop:

然后,您可以轻松地循环访问这些标签:

for(int i = 1; i <= 100; i++)
{
    [[self.view viewWithTag:i] setText:[NSString stringWithFormat:@"Output%d.text",i]];
}

If you have not already created all the labels in a view, i would suggest creating the labels programmatically, in a loop and set the tags. Since you can easily access them using the tags, you need not declare them as properties either.

如果您尚未在视图中创建所有标签,我建议以编程方式在循环中创建标签并设置标签。由于您可以使用标签轻松访问它们,因此您也无需将它们声明为属性。

回答by DoS

i may be a little late to the show here. i am not quite sure if you are wanting to name the uilabels or set the text property of the uilabels? from your example code it looks like you are trying to set the text, given you have said you synthesized them already. if thats the case, i can name that tune with one line, bob! kvc (key-value coding) i think if your best bet...

我在这里的演出可能有点晚了。我不太确定您是要命名 uilabels 还是设置 uilabels 的 text 属性?从您的示例代码来看,您似乎正在尝试设置文本,因为您已经说过您已经合成了它们。如果是这样的话,我可以用一句话来命名那首曲子,鲍勃!kvc(键值编码)我想如果你最好的选择......

for (int i=1; i< 101; i++)
{
    [self setValue:[NSString stringWithFormat:@"%i", i] forKeyPath:[NSString stringWithFormat:@"output%i.text", i]];
} 

the end result would be like doing this...

最终结果就像这样做......

output1.text = @"1";
// repeat...
output100.text = @"100";

if you wanted to set the tags you could do the same with...

如果你想设置标签,你可以做同样的事情......

for (int i=1; i< 101; i++)
    {
        [self setValue:i forKeyPath:[NSString stringWithFormat:@"output%i.tag", i]];
    } 

that end result would be like doing this...

最终结果就像这样做......

output1.tag = 1;
// repeat...
output100.tag = 100;

of course you could put both routines in the same for loop if you wanted. if this is what you are after, i would recommend changing your code to this. it's by far the most efficient and "apple like" way of doing it. you could change things around and tweak it how ever you want to make what ever dynamic changes you want. it's a very cool method. it cut down almost 500 lines of code in one of my projects once i figured this out. it's amazing what you learn when you actually read the docs.

当然,如果您愿意,您可以将两个例程放在同一个 for 循环中。如果这是您所追求的,我建议您将代码更改为此。这是迄今为止最有效和“像苹果一样”的方式。你可以改变事情并调整它,无论你想要什么都可以做出你想要的动态变化。这是一个非常酷的方法。一旦我弄清楚了这一点,它就在我的一个项目中减少了近 500 行代码。当你真正阅读文档时,你学到的东西是惊人的。