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()
}
}
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 abackgroundColor, otherwise it will just be black.Note: You don't have to explicitly call
drawLine, becausedraw(rect:)will be called by the system when the view appears.Also, you only need one
UIBezierPath:Note: A
lineWidthof0.1is a really thin line and may not be very visible. A one point line is1, and a one pixel line would be0.3333or0.5on current iPhones.