Search code examples
swiftuiviewconstraintscenterlayer

draw line in place of x axis in view controller


I want my swift code to draw a line like the place of a x axis. So the line is in the center of the screen no matter what screen size the object is displayed in. My code below produces a line but it does not account for the device size. My image below displays a black line which is what my current code produces and the orange line is the desired output.

Pic

    import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let lineView = UIView(frame: CGRect(x: 0, y: 100, width: 320, height: 1.0))
        lineView.layer.borderWidth = 1.0
        lineView.layer.borderColor = UIColor.black.cgColor
        self.view.addSubview(lineView)
    }


}

Solution

  • To draw a line in the middle of the screen, just assign the Line.swift file to UIView on which you want to draw a line.

    Line.swift file

    class Line:UIView {
    
    var line =  UIBezierPath()
    
    func drawLine() {
        line.move(to: CGPoint(x: 0, y: bounds.height / 2))
        line.addLine(to: CGPoint(x: (bounds.width) , y: bounds.height / 2))
        UIColor.black.setStroke()
        line.lineWidth = 0.1
        line.stroke()
    
    }
    
    override func draw(_ rect: CGRect) {
             drawLine()
           }
        }
    

    To assign it to your UIView, open the main.storyboard and click on the view where you want to draw the line. Then, go into upper right tabs which would look like this

    enter image description here

    You can see inside the class field, there is a placeholder called "UIView". Type there Line and hit enter, and then just run the project. You 'll be able to see the line in the middle of the view. No need to declare or call any function. Just assign this class and run the project.