【问题标题】:Using NSString value to refer to UILabel使用 NSString 值来引用 UILabel
【发布时间】:2012-01-24 14:08:04
【问题描述】:

请原谅,这里的新手。

我有一个动态构建的 NSString 值,它是 UILabel 实例的名称。我想向标签发送消息以更新其文本。但是,这两种数据类型不匹配。这里有足够的代码(我认为):

在头文件中:

IBOutlet UILabel *Clue1; // IBOutlet and IBAction are IDE flags
IBOutlet UILabel *Clue2; // IB = interface builder
IBOutlet UILabel *Clue3;

在实现文件中:

- (IBAction) newPuzzle:(id)sender { // Clear all fields & get new clue

    [Clue1 setText:@""]; // Clear the fields
    [Clue2 setText:@""]; 
    [Clue3 setText:@""]; 

    // Send up a randomly chosen new clue

    NSArray *clues = [NSArray arrayWithObjects:@"222", @"333", nil];
    NSInteger randomIndex = arc4random()%[clues count];
    NSString *aClue = [clues objectAtIndex:randomIndex];

    // The clue will be split into component digits and each piece sent to a different label

    for (NSInteger charIdx = 0; charIdx < aClue.length; charIdx++) {
        NSString *cluePos = [NSString stringWithFormat:@"Clue%d", charIdx + 1];
        NSLog(@"%@", cluePos); // works
        [cluePos setText:@"test"]; // Xcode notes the type mismatch
    }
}

关于 SO 有一些类似的问题,但没有一个足够接近让我认识到它们适用于我的案例,至少据我所知。使用另一种语言 (R) 的术语,我需要“强制”从 NSString 到 UILabel 的线索位置类。我在 Xcode 4.2.1 和 OSX 10.7.2 上。

TIA。

【问题讨论】:

    标签: objective-c ios


    【解决方案1】:

    您不能将字符串强制转换为标签,因为它们根本不同。该字符串不了解您的视图控制器类或其属性(其中一些恰好是标签)。

    但是,您可以使用 valueForKey: 方法按名称获取对象的属性,其中名称指定为字符串。所以要在我的视图控制器上获得一个名为 Clue1 的属性,我会说:

    UILabel *label = [self valueForKey:@"Clue1"];
    

    或者在你的情况下,这个:

    NSString *cluePos = [NSString stringWithFormat:@"Clue%d", charIdx + 1];
    UILabel *label = [self valueForKey:cluePos];
    label.text = @"test";
    

    (在这种情况下,我假设 'self' 指的是视图控制器,但您可以在任何具有属性的对象上调用它。)

    另一种方法是使用 NSSelectorFromString 将字符串转换为选择器。看起来像这样:

    SEL selector = NSSelectorFromString(@"Clue1");
    UILabel *label = [self performSelector:selector];
    

    出于您的目的,两种解决方案都同样适用,但是使用选择器的优点是您可以将参数传递给方法调用(因此您可以调用返回对象的方法,而不仅仅是访问属性或 IBOutlet)。

    请注意,如果您尝试访问属性或调用不存在的方法,这两种方法都会引发异常。您可以在调用它之前测试该属性是否存在:

    SEL selector = NSSelectorFromString(@"Clue1");
    BOOL labelExists = [self respondsToSelector:selector];
    if (labelExists)
    {
        UILabel *label = [self performSelector:selector];
        label.text = @"test";
    }
    else
    {
        //do something else
    }
    

    【讨论】:

    • 太好了,谢谢,它有效。我需要稍微研究一下 valueForKey 和属性,以准确了解替换是如何工作的。而不是 label.text = @"test" 我希望文本是一个变量,特别是我想传递 [aClue characterAtIndex:charIdx] 作为要显示的值。你能建议怎么做吗?仍然在学习!谢谢。
    • 要获取给定索引处的字符,请尝试 [aClue substringWithRange:NSMakeRange(charIdx, 1)]。这会返回一个长度为一个字符的字符串,这比 unichar 更容易使用。
    • 谢谢你,就像一个魅力。让我学习更多,但这是我最好的学习方式。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多