2017年12月27日 星期三

swift4 自定義layer框線(border)

今天分享自定義layer匡線,有時候在設計上可能會有框架框線顏色兩種或三種,
但原生的通常就是讓你簡單方便,一個框架一個顏色。

下面範例就是原生整個框架顏色,我直接使用ViewController的View來給予範例如下:
self.view.layer.borderColor = UIColor.blue.cgColor;

self.view.layer.borderWidth = 10.0;

但是有時可能會需要多個label拼成一個大的並且有框架之類的時候,
又剛好只有最外圈框架顏色不同就很麻煩了,
有些人可能會選擇偷懶做一個View覆蓋在上面讓backgroundcolor是透明的,
然後給予框線並符合原本物件所需大小。

今天這邊要跟大家分享的就是寫一個CALayer的擴充來達到目的,
我建立了幾個物件,一個UILabel、一個UIButton、一個UITextField、一個UIView來呈現效果。
首先我們要先寫一個擴充如下:

extension CALayer{
    func addBorder(edge:UIRectEdge, color:UIColor, thickness:CGFloat){
        
        let borders = CALayer()
        
        switch edge {
        case .top:
            borders.frame = CGRect(x: 0, y: 0, width: frame.width, height: thickness);
            break
        case .bottom:
            borders.frame = CGRect(x: 0, y: frame.height - thickness, width: frame.width, height: thickness);
        case .left:
            borders.frame = CGRect(x: 0, y: 0 + thickness, width: thickness, height: frame.height - thickness * 2);
        case .right:
            borders.frame = CGRect(x: frame.width - thickness, y: 0 + thickness, width: thickness, height: frame.height - thickness * 2);
        default:
            break
        }
        
        borders.backgroundColor = color.cgColor;
        
        self.addSublayer(borders);
    }
}

這個擴充東西並不多,其實很簡短,
有人會好奇為什麼有的我會-thickness甚至做成-thickness * 2原因很簡單,
這可以依照個人喜好去做,我會做-thickness * 2 是因為那是左右兩邊,
而我不希望他有被覆蓋或是覆蓋到上或下的邊框,
所以我剪去thickness的兩倍讓他高度是去除上下邊框的高度。
但前提是你的框架寬(高)度必須是一致的。

寫好擴充後就剪得了,接下來你只要做以下範例動作就能夠產生邊框了喔!

 V1.layer.addBorder(edge: .top, color: .red, thickness: 5.0);
 V1.layer.addBorder(edge: .bottom, color: .blue, thickness: 5.0);
 V1.layer.addBorder(edge: .left, color: .green, thickness: 5.0);
 V1.layer.addBorder(edge: .right, color: .yellow, thickness: 5.0);

 btn.layer.addBorder(edge: .top, color: .brown, thickness: 2.0);
 btn.layer.addBorder(edge: .bottom, color: .gray, thickness: 2.0);
 btn.layer.addBorder(edge: .left, color: .red, thickness: 2.0);
 btn.layer.addBorder(edge: .right, color: .blue, thickness: 2.0);

 label.layer.addBorder(edge: .top, color: .black, thickness: 2.0);
 label.layer.addBorder(edge: .bottom, color: .gray, thickness: 2.0);
 label.layer.addBorder(edge: .left, color: .purple, thickness: 2.0);
 label.layer.addBorder(edge: .right, color: .orange, thickness: 2.0);

 text.layer.addBorder(edge: .top, color: .red, thickness: 2.0);
 text.layer.addBorder(edge: .bottom, color: .cyan, thickness: 2.0);
 text.layer.addBorder(edge: .left, color: .magenta, thickness: 2.0);
 text.layer.addBorder(edge: .right, color: .darkGray, thickness: 2.0);

看起來很多,是因為這種寫法就變成你每一個框都要去寫一次,
畢竟你可能四邊顏色都不同之類的,
最後附上運行出來的成果圖如下:

希望能夠幫助到有需要的朋友們!