swift_dev25 swift_dev25 - 14 days ago 6
iOS Question

Swift UITableView zigzag borders

I am trying to achieve this aspect for an UITableView : https://www.dropbox.com/s/bcp86myyjgek1kt/Screenshot%202016-11-04%2014.04.14.png?dl=0 and I am stuck.

I followed Atul Manwar's answer :

func applyZigZagEffect(givenView: UIView) {
let width = givenView.frame.size.width
let height = givenView.frame.size.height

let givenFrame = givenView.frame
let zigZagWidth = CGFloat(7)
let zigZagHeight = CGFloat(5)
let yInitial = height-zigZagHeight

var zigZagPath = UIBezierPath()
zigZagPath.moveToPoint(CGPointMake(0, 0))
zigZagPath.addLineToPoint(CGPointMake(0, yInitial))

var slope = -1
var x = CGFloat(0)
var i = 0
while x < width {
x = zigZagWidth * CGFloat(i)
let p = zigZagHeight * CGFloat(slope)
let y = yInitial + p
let point = CGPointMake(x, y)
zigZagPath.addLineToPoint(point)
slope = slope*(-1)
i++
}
zigZagPath.addLineToPoint(CGPointMake(width, 0))

var shapeLayer = CAShapeLayer()
shapeLayer.path = zigZagPath.CGPath
givenView.layer.mask = shapeLayer
}


The result is not the one I am looking for, because I only obtain the bottom border: Achieved using Atul's answer and I have no clue how to change it for both borders ( bottom and top ).

Tried with images, but is not scaled correctly, and I find this solution better, but I am not able to produce the effect for top border.

Thanks!

Answer

I had been working on your question and this are my results, use this code,

enter image description here

func applyZigZagEffect(givenView: UIView) {
    let width = givenView.frame.size.width
    let height = givenView.frame.size.height

    let givenFrame = givenView.frame
    let zigZagWidth = CGFloat(7)
    let zigZagHeight = CGFloat(5)
    var yInitial = height-zigZagHeight

    var zigZagPath = UIBezierPath(rect: givenFrame)
    zigZagPath.move(to: CGPoint(x:0, y:0))
    zigZagPath.addLine(to: CGPoint(x:0, y:yInitial))

    var slope = -1
    var x = CGFloat(0)
    var i = 0
    while x < width {
        x = zigZagWidth * CGFloat(i)
        let p = zigZagHeight * CGFloat(slope)
        let y = yInitial + p
        let point = CGPoint(x: x, y: y)
        zigZagPath.addLine(to: point)
        slope = slope*(-1)
        i += 1
    }

    zigZagPath.addLine(to: CGPoint(x:width,y: 0))

    yInitial = 0 + zigZagHeight
    x = CGFloat(width)
    i = 0
    while x > 0 {
        x = width - (zigZagWidth * CGFloat(i))
        let p = zigZagHeight * CGFloat(slope)
        let y = yInitial + p
        let point = CGPoint(x: x, y: y)
        zigZagPath.addLine(to: point)
        slope = slope*(-1)
        i += 1
    }

    var shapeLayer = CAShapeLayer()
    shapeLayer.path = zigZagPath.cgPath
    givenView.layer.mask = shapeLayer
}

I hope this helps you, this code works and was tested