Skip to content

Instantly share code, notes, and snippets.

@maxcampolo
Last active July 4, 2023 07:12
Show Gist options
  • Save maxcampolo/8493e7a1bc9854b67d5f to your computer and use it in GitHub Desktop.
Save maxcampolo/8493e7a1bc9854b67d5f to your computer and use it in GitHub Desktop.
Extension that adds a tag property to UIViewController
/*
*
* This class provides a UIViewController extension which adds a tag property to all UIViewController subclasses.
*
*/
import Foundation
private var tagAssociationKey: UInt8 = 0
extension UIViewController {
public var tag: String! {
get {
return objc_getAssociatedObject(self, &tagAssociationKey) as? String
}
set(newValue) {
objc_setAssociatedObject(self, &tagAssociationKey, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN))
}
}
}
@jjxtra
Copy link

jjxtra commented Sep 22, 2016

Objective-C?

@League2EB
Copy link

update for Swift 5

    public var tag: String {
        get {
            return objc_getAssociatedObject(self, &tagAssociationKey) as? String ?? "❤️"
        }
        set(newValue) {
            objc_setAssociatedObject(self, &tagAssociationKey, newValue, .OBJC_ASSOCIATION_RETAIN)
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment