Вопрос

I created a simple UILabel and I want to add for it a name and use it in if statement. I think I need valueforkey but I have no idea how to get it in the if statement.

Here's the code I tried:

UILabel *labl = [[UILabel alloc]init];
labl.text = @"Kmartin";
labl.textColor = [UIColor whiteColor];
labl.enabled = YES;
labl.bounds = CGRectMake(0, 0, 190, 190);
labl.center = CGPointMake(tx, 320);
labl = [self valueForKey:@"nm1"];
[self.view addSubview:labl];
if ([labl valueForKey:@"name 1"]){
    NSLog(@"yes");
}else{
    NSLog(@"no");
}  
Это было полезно?

Решение

use the tag property

labl.tag = 1;

if (labl.tag == 1){
    NSLog(@"yes");
}else{
    NSLog(@"no");
} 

Другие советы

If tag is not convenient, use core library features:

#import <objc/runtime.h>
static int nameAssociationKey;

objc_setAssociatedObject(label, &nameAssociationKey, @"My Label Name",
                         OBJC_ASSOCIATION_COPY_NONATOMIC);
NSString *name = objc_getAssociatedObject(label, &nameAssociationKey);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top