Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save christianselig/f4c076688fd11d45c5dcccab20b7fee9 to your computer and use it in GitHub Desktop.
Save christianselig/f4c076688fd11d45c5dcccab20b7fee9 to your computer and use it in GitHub Desktop.
Swizzle UITableViewHeaderFooterView to make header color customizable. Done in willMoveToWindow (once) because it should occur right before visible.
extension UITableViewHeaderFooterView {
private static var hasFiredOnceKey = "apollo_hasFiredOnceKey"
static func apollo_swizzle() {
// To be called in AppDelegate.didFinishLaunching
let originalSelector = #selector(willMove(toWindow:))
let swizzledSelector = #selector(apollo_willMove(toWindow:))
guard let originalMethod = class_getInstanceMethod(self, originalSelector), let swizzledMethod = class_getInstanceMethod(self, swizzledSelector) else {
assertionFailure("Original method or swizzled method is unavailable")
return
}
let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
if didAddMethod {
class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
@objc func apollo_willMove(toWindow newWindow: UIWindow?) {
apollo_willMove(toWindow: newWindow)
let hasFiredOnce = ((objc_getAssociatedObject(self, &UITableViewHeaderFooterView.hasFiredOnceKey) as? NSNumber)?.boolValue) ?? false
guard !hasFiredOnce else { return }
objc_setAssociatedObject(self, &UITableViewHeaderFooterView.hasFiredOnceKey, NSNumber(booleanLiteral: true), .OBJC_ASSOCIATION_RETAIN)
// πŸš’ πŸš’ πŸš’ πŸš’ πŸš’ πŸš’ πŸ§‘β€πŸš’
textLabel?.textColor = .red
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment