Skip to content

Instantly share code, notes, and snippets.

@manjuhere
Last active October 23, 2019 06:08
Show Gist options
  • Save manjuhere/3ce6a689986218dd8f16797c5ec374ac to your computer and use it in GitHub Desktop.
Save manjuhere/3ce6a689986218dd8f16797c5ec374ac to your computer and use it in GitHub Desktop.
Add & Remove borders on a UIView for various positions.
//
// UIView+Border.swift
//
// Created by Manjunath Chandrashekar on 03/11/18.
// Copyright © 2018 Manjunath Chandrashekar. All rights reserved.
//
import Foundation
extension UIView {
enum BorderPosition: String {
case top = "topBorder"
case right = "rightBorder"
case bottom = "bottomBorder"
case left = "leftBorder"
}
func addBorder(position: BorderPosition, color: UIColor = .gray, width: CGFloat = 2.0) {
for layer in self.layer.sublayers ?? [] {
// If layer already exists, remove it before adding again.
if position.rawValue == layer.name {
layer.removeFromSuperlayer()
}
}
let border = CALayer()
border.name = position.rawValue
border.backgroundColor = color.cgColor
switch position {
case .top:
border.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: width)
case .right:
border.frame = CGRect(x: self.frame.size.width - width, y: 0, width: width, height: self.frame.size.height)
case .bottom:
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: width)
case .left:
border.frame = CGRect(x: 0, y: 0, width: width, height: self.frame.size.height)
}
self.layer.addSublayer(border)
}
func removeBorder(position: BorderPosition) {
for layer in self.layer.sublayers ?? [] {
if position.rawValue == layer.name {
layer.removeFromSuperlayer()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment