UIView extension for add/remove border

Updated:
Categories: iOS
Tags: #iOS #Swift3 #UIView

iOS UIView 방향별 border 추가/삭제Permalink

iOS에서 Swift3로 UIView의 top, bottom, left, right 에 border 추가/삭제할 수 있는 코드. extension을 이용하여, UIView에서 해당 함수를 접근할 수 있음.

extension UIView {
// Example use: myView.addBorder(toSide: .Left, withColor: UIColor.redColor().CGColor, andThickness: 1.0)
enum ViewSide: String {
case Left = "Left", Right = "Right", Top = "Top", Bottom = "Bottom"
}
func addBorder(toSide side: ViewSide, withColor color: CGColor, andThickness thickness: CGFloat) {
let border = CALayer()
border.borderColor = color
border.name = side.rawValue
switch side {
case .Left: border.frame = CGRect(x: 0, y: 0, width: thickness, height: frame.height)
case .Right: border.frame = CGRect(x: frame.width - thickness, y: 0, width: thickness, height: frame.height)
case .Top: border.frame = CGRect(x: 0, y: 0, width: frame.width, height: thickness)
case .Bottom: border.frame = CGRect(x: 0, y: frame.height - thickness, width: frame.width, height: thickness)
}
border.borderWidth = thickness
layer.addSublayer(border)
}
func removeBorder(toSide side: ViewSide) {
guard let sublayers = self.layer.sublayers else { return }
var layerForRemove: CALayer?
for layer in sublayers {
if layer.name == side.rawValue {
layerForRemove = layer
}
}
if let layer = layerForRemove {
layer.removeFromSuperlayer()
}
}
}

참고: https://stackoverflow.com/a/32513578

Comments