View decoration in Swift

Tram Ho

I. Introduction

Clean code is something every developer has to do. But keeping the code clean and easy to read requires a lot of factors. Whenever I have free time, I would rummage through the code of projects I have made. Psychology everyone when opening up to review their achievements, it is difficult to “smell”  A new project has gained a bit of experience and is proud again. But just done and review it again that something is not right. I have a fairly common case that I and most of you have encountered:

In a project the views are quite similar and each time I write the same code. The feeling of re-reading the code is quite annoying . But then I thought of a way of writing into Constant. This has helped me no longer have duplicated code, but changing the way I want is difficult. So is there any way?

II. Solution

You want to customize a UIVIew like interface. Has 4-sided corners and shadow? First you create a protocol called ViewDecorator.

Which has a method. Call method with input as a UIView. To make custom UI simpler. I created an extension for UIView. With the extension, setting properties for UIView will not need to call again.

extension UIView {

And now we create more struct to implement what we want and see how this works. First I create a struct to set the rounded corners for UIView as follows

Add a struct to set shadow for UIView

Now is the stage of implementing what we have done. We can call both decorate at the same time as follows:

This is just one of hundreds of cases where we can shorten our code. You refer and we together “unmask” the cases we have encountered and solutions to improve together offline.

III. Conclude

There is a saying: A good programmer must code for others to understand, not just code to run. In my opinion this is not only done in a day or two, but it is the goal that I set on top of every work

Reference link: https://medium.com/halcyon-mobile/view-decoration-in-swift-4023a68be5d3

Share the news now

Source : Viblo