Prajeet Shrestha Prajeet Shrestha - 1 year ago 90
Objective-C Question

How to reduce code redundancy while subclassing views?

I have a requirement where I need to alter UIComponents like UIButton, UIView and UITextField. What I need to do is just to make change the radius of border to round rather than sharp rectangle which is default.

The way I have done this is to subclass UIView to UIViewRoundCorner, UIButton to UIButtonRoundCorner, UITextField to UITextFieldRoundCorner and inside each subclass I have overridden the drawRect Method with this:

- (void)drawRect:(CGRect)rect {
// Drawing code
CALayer *layer = [self layer];
[layer setMasksToBounds:YES];
[layer setCornerRadius:3.0f];
[layer setBorderWidth:1.0f];

The code is redundant and I am trying to figure out how to remove this redundancy. Since all these element is being inherited from UIView, is it possible somehow to subclass UIView and implement in all the other views?

Answer Source
protocol RoundedCorner {
    func makeCornerRadius(radius:CGFloat)

extension RoundedCorner where Self:UIView{
    func makeCornerRadius(radius:CGFloat){
        self.layer.cornerRadius = radius

class CustomButton: UIButton, RoundedCorner {

    override func drawRect(rect: CGRect) {

you can create a protocol and extend that protocol for default implementation. and then for every custom view for which you want corner radius, just implement that protocol. This way you can minimise your code redundancy.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download