miDark miDark - 1 year ago 93
iOS Question

Can we get UILabel's name?

I was wondering if it is possible to get the name of a

(not the text).

Something like this:

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

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

Answer Source

The simplest way is to extend UILabel and add the name property like this:

extension UILabel {
    var name : String {
        get {
            return self.name
        set(newValue) {
            self.name = newValue

Note: This works for both Objective-C and Swift. For Objective-C: You can write a Swift extension and use it in Objective-C code. All you need to do is import the XCode target the Swift extension is associated with. Source: Can objective-c code call swift extension on Class?

Additionally, you could subclass UILabel:

// Objective-C

#import <UIKit/UIKit.h>

@interface NMLabel : UILabel

@property (nonatomic, readwrite) NSString *name;


// Swift

class NMLabel : UILabel {

    var name : String = ""


Note: Do not try doing this method along with the first method

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download