Every then and now I am having a task of implementing a custom button. Often they are pretty simply having text only, so normal UIButton can do. But sometimes, designers like to challenge me and they create something more complex. Imagine a button like this:

As a developer, when I see something like that I am used creating a simple UIView with everything inside. Later, I would add a TapGestureRecognizer to it and voilà it’s done!

Not necessary. If you are a mobile developer then for sure you have seen that buttons change the colour when they are pressed. And that’s the problem. Having a UIView instead of the button you are missing the highlight state.

UIButton for the rescue?

At some point, I thought that I can’t use UIViews anymore. I realized I need to do something about it (no, it wasn’t a client or designer that spotted it, it was me). I opened Visual Studio for Mac and thought of a solution on how to achieve it. I started taking a deep dive into UIButton’s documentation. As a result, I’ve found out that UIButton has a method AddSubview. “That’s cool! Let’s use it” – I thought. I created a UIView with proper content for my Button and UIButton. Finally, I connected everything together – I added my UIView to the Button.

buttonView.UserInteractionEnabled = false;
AddSubview(buttonView);buttonView.LeftAnchor.ConstraintEqualTo(LeftAnchor).Active = true;
buttonView.TopAnchor.ConstraintEqualTo(TopAnchor).Active = true;
buttonView.RightAnchor.ConstraintEqualTo(RightAnchor).Active = true;
buttonView.BottomAnchor.ConstraintEqualTo(BottomAnchor).Active = true;

Of course, knowing the AddSubview I added needed constraints. Proud of myself that I solved the thing that bothers me for a long time I run the app. Guess what…

It was not working as expected. Despite the fact that I was using UIButton, it wasn’t highlighted when it was pressed.

After further digging I found several issues saying that the highlight colour is missing when the subview was added. Great…

Creativity FTW

Considering what I had created I was not willing to give up. I felt like what I wanted to have is at my fingertips. I didn’t give up.

I thought that maybe we can subscribe to TouchEvents and add a semi-transparent overlay over the button. It sounded promising so, I implemented it. On TouchDown, I added an overlay and on TouchUp I remove it.

This is what I was able to achieve:

RESULT

Let’s take a look at something that you’ve probably come for.

Conclusion

I decided to share this article with you as I believe many developers would like to have a “normal” button but don’t have time to figure it out.
I plan to create this kind of a button for Android. Later, I would love to have it for Xamarin.Forms so later I can pack everything into a Nuget and distribute. I will definitely keep you updated!

Leave a Reply

Your email address will not be published. Required fields are marked *