Search code examples
swiftsubclassuibezierpathaddsubview

connect uibezierpath with a another class


My swifts code goal is to draw a line representing both they x and y axis lines like you would see in a graph. I have the code I used to create the graph but I dont know how to connect to the view controller classes. I thing I have to create a object in the view controller and subclass it with another classes in this case would be class line. I just thought my code below would work but nothing is appearing.

import UIKit

class ViewController: UIViewController{
    var box = Line()
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(box)
        box.drawLine()
        
    }

 
}

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

Solution

  • Two things: you need to give your box a frame (or give it some constraints to set its size), and you need to give it a backgroundColor, otherwise it will just be black.

    override func viewDidLoad() {
        super.viewDidLoad()
    
        let box = Line(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
        box.backgroundColor = .white
        view.addSubview(box)
    }
    

    Note: You don't have to explicitly call drawLine, because draw(rect:) will be called by the system when the view appears.

    Also, you only need one UIBezierPath:

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

    Note: A lineWidth of 0.1 is a really thin line and may not be very visible. A one point line is 1, and a one pixel line would be 0.3333 or 0.5 on current iPhones.