Karthikeyan Sk
Karthikeyan Sk

Reputation: 350

Ios - Is there a way to draw a line in UIViewController without using code

I want to draw a line in UIViewController without using code, so like the constraints for the lines can be given in storyboard itself. if there is a way to do it, please tell me. Now i have drawn a line by placing an UIView in storyboard and used the following code to draw line on it. Is this the best way ?. Or do i have any better way ?. Thanks in advance.

class line: UIView {

    override func draw(_ rect: CGRect) {
        let aPath = UIBezierPath()

        aPath.move(to: CGPoint(x:0, y:1))

        aPath.addLine(to: CGPoint(x:500, y:1))

        //Keep using the method addLineToPoint until you get to the one where about to close the path

        aPath.close()

        //If you want to stroke it with a red color
        UIColor.blue.set()
        aPath.stroke()
        //If you want to fill it as well
        aPath.fill()
    }
}

Using Swift 3.0 and Xcode 8.2

Upvotes: 3

Views: 1466

Answers (2)

Magnas
Magnas

Reputation: 4054

Use @IBDesignable as follows. Make your view with height of one as suggested and the @IBDesignable will show your line in your storyboard.:

import UIKit

@IBDesignable class line: UIView {

    override func draw(_ rect: CGRect) {
        let aPath = UIBezierPath()
        aPath.move(to: CGPoint(x: 0, y: 1))
        aPath.addLine(to: CGPoint(x: 250, y: 1))
        aPath.close()
        UIColor.blue.set()
        aPath.stroke()
    }
}

Upvotes: 3

Dhiraj Das
Dhiraj Das

Reputation: 174

Add a UIView with a height of 1 point. Add constraints for it.

Upvotes: 1

Related Questions