Created
January 5, 2018 08:16
-
-
Save softlion/fd43d16c17a248e01a7a5d7a75c59347 to your computer and use it in GitHub Desktop.
Xamarin objc_getAssociatedObject / objc_setAssociatedObject snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ParallaxHeader : UIView | |
{ | |
public UIScrollView ScrollView { get; set; } | |
} | |
public static class ParallaxHeaderExtension | |
{ | |
private static readonly NSString DescriptiveName = new NSString("Vapolia." + nameof(ParallaxHeader)); | |
enum AssociationPolicy { | |
//ASSIGN = 0, | |
RETAIN_NONATOMIC = 1, | |
//COPY_NONATOMIC = 3, | |
//RETAIN = 01401, | |
//COPY = 01403, | |
} | |
[DllImport("/usr/lib/libobjc.dylib")] | |
static extern void objc_setAssociatedObject(IntPtr obj, IntPtr key, IntPtr value, AssociationPolicy policy); | |
[DllImport ("/usr/lib/libobjc.dylib")] | |
static extern IntPtr objc_getAssociatedObject (IntPtr obj, IntPtr key); | |
public static ParallaxHeader GetParallaxHeader(this UIScrollView scrollView) | |
{ | |
var handle = objc_getAssociatedObject(scrollView.Handle, DescriptiveName.Handle); | |
if(handle != IntPtr.Zero) | |
{ | |
var value = ObjCRuntime.Runtime.GetNSObject(handle); | |
if (value != null) | |
return (ParallaxHeader)value; | |
} | |
var ph = new ParallaxHeader(); | |
scrollView.SetParallaxHeader(ph); | |
return ph; | |
} | |
public static void SetParallaxHeader(this UIScrollView scrollView, ParallaxHeader parallaxHeader) | |
{ | |
parallaxHeader.ScrollView = scrollView; | |
objc_setAssociatedObject(scrollView.Handle, DescriptiveName.Handle, parallaxHeader.Handle, AssociationPolicy.RETAIN_NONATOMIC); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment