Skip to content

Instantly share code, notes, and snippets.

@softlion
Created January 5, 2018 08:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save softlion/fd43d16c17a248e01a7a5d7a75c59347 to your computer and use it in GitHub Desktop.
Save softlion/fd43d16c17a248e01a7a5d7a75c59347 to your computer and use it in GitHub Desktop.
Xamarin objc_getAssociatedObject / objc_setAssociatedObject snippet
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