5

I was wondering if it is possible to get the name of a UILabel (not the text).

Something like this:

if([label.name is equalToString:key]){
     //do something
}

I know label.name doesn't exist but maybe there is something equivalent. How can I do this?

Wyetro
  • 8,439
  • 9
  • 46
  • 64
miDark
  • 83
  • 9
  • 4
    You could subclass UILabel and add it. You could extend it. Or you could use the tag property which returns an Int. – Wyetro Sep 02 '16 at 14:17
  • Please check the answer to this question: http://stackoverflow.com/questions/3958852/how-to-access-object-id-identity-attribute – L A Sep 02 '16 at 14:19
  • ty !! tag property is perfect – miDark Sep 02 '16 at 14:21
  • Could you define your use? Because, if they are all IBOutlet and if it's in a IBAction as sender, or a delegate method, you could use `if (_myLabelOutlet1 == label)`, use tag, or add property with subclassing... – Larme Sep 02 '16 at 14:26
  • i need the label's name because i want to [label setText] switch the name of the label.. i will use tag, and then i can use switch/case – miDark Sep 02 '16 at 14:30
  • @miDark If you really want to use a name and not just an int value I'd highly recommend looking at the other two methods I mentioned in my answer. – Wyetro Sep 02 '16 at 14:32
  • oh ty ! i will try the answer with swift extension – miDark Sep 02 '16 at 14:39
  • @miDark, good idea. It's easy to implement, especially if you already have a bunch of UILabels and don't want to subclass (especially for such a small change to the class). – Wyetro Sep 02 '16 at 14:53

1 Answers1

4

You could subclass UILabel:

// Objective-C

#import <UIKit/UIKit.h>

@interface NMLabel : UILabel

@property (nonatomic, readwrite) NSString *name;

@end


// Swift
import UIKit

class NMLabel : UILabel {

    var name : String = ""

}

Or at the most basic of levels you can use the already existent tag property (in both Objective-C or Swift):

label.tag = 5

// Objective-C

NSLog(@"%d", label.tag); // prints 5

// Swift

print(label.tag) // prints 5
Wyetro
  • 8,439
  • 9
  • 46
  • 64