Xamarin – User interaction with image views

It’s sometimes the simplest of things I tend to overlook when debugging.

While recently working on one of my company’s mobile apps, I came across an issue which had me stomped for a good 30 minutes before realizing how easy it was to resolve.

Part of the work involved creating custom views in our app to display mobile ads.  UIImageViews to be exact.  This view contains a full screen image, and a close button at the top right of the view to dismiss the ad.  Simple, right!  Well, the problem was no matter what I did, the close button did not respond to any touch events.

As you can see from the code sample below we’ve taken the route of using C# to create some of our views.  Here is what the constructor of the subclassed UIImageView looked like before solving the problem.

public FullPageAdView(float adWidth, float adHeight, Ads ads) : base(new RectangleF(0, 0, adWidth, adHeight))
{
if (ads == null)
throw new ArgumentException("Mobile Ads are missing");

MobileAds = ads;
closeButton = UIButton.FromType(UIButtonType.Custom);
closeButton.SetImage(UIImage.FromBundle(“RedCloseButton.png”), UIControlState.Normal);
closeButton.SetImage(UIImage.FromBundle(“RedCloseButtonClicked.png”), UIControlState.Selected);
closeButton.TouchUpInside += OnCloseButtonClicked;
AddSubview(closeButton);

}

We’ve properly registered the TouchUpInside button event and added the button to our custom view.  Should just work right…NOPE!  Turns out many of the controls in UIKit, including UIImageView, do not have touch enabled by default.  It has to be turned on as you can see in the snippet below.


public FullPageAdView(float adWidth, float adHeight, Ads ads) : base(new RectangleF(0, 0, adWidth, adHeight))
{
if (ads == null)
throw new ArgumentException("Mobile Ads are missing");

MobileAds = ads;
closeButton = UIButton.FromType(UIButtonType.Custom);
closeButton.SetImage(UIImage.FromBundle(“RedCloseButton.png”), UIControlState.Normal);
closeButton.SetImage(UIImage.FromBundle(“RedCloseButtonClicked.png”), UIControlState.Selected);
closeButton.TouchUpInside += OnCloseButtonClicked;
AddSubview(closeButton);
this.UserInteractionEnabled = true;
}

If you are using Xcode to create your image view, here is what the option looks like (borrowed image from here).

image1

And there you have it. Simple solution to a simple problem.

I hope this saves someone else the hassle and time I spent in resolving this issue.

Happy Xamarin trails!

Advertisements
Tagged , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: