Step 1 –  Create view extension 

Create new file – UIView+Extension.swift

import Foundation
import UIKit

extension UIView {
    
    func addBorderTop(size: CGFloat, color: UIColor) {
        addBorderUtility(x: 0, y: 0, width: frame.width, height: size, color: color)
    }
    func addBorderBottom(size: CGFloat, color: UIColor) {
        addBorderUtility(x: 0, y: frame.height - size, width: frame.width, height: size, color: color)
    }
    func addBorderLeft(size: CGFloat, color: UIColor) {
        addBorderUtility(x: 0, y: 0, width: size, height: frame.height, color: color)
        
    }
    func addBorderRight(size: CGFloat, color: UIColor) {
        addBorderUtility(x: frame.width - size, y: 0, width: size, height: frame.height, color: color)
    }
    private func addBorderUtility(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, color: UIColor) {
        let border = CALayer()
        border.backgroundColor = color.cgColor
        border.frame = CGRect(x: x, y: y, width: width, height: height)
        layer.addSublayer(border)
    }
}

Step 2 – Call extension method wherever required 

For example:

btn.addBorderLeft(size: 5, color: UIColor.red)

lbl.addBorderTop(size: 5, color: UIColor.red)

240_F_77959340_hWLiOY93juohUoXqjKzqPB79552nw8XU

Hope you find this blog useful. Please feel free to contact with me in case you have any query, suggestions.  You can comment, like and follow posts.

You can request any topic related to Swift and iOS development.

Advertisements