//: Playground - noun: a place where people can play import UIKit import PlaygroundSupport class ViewController: UIViewController { let W: CGFloat = 400 let H: CGFloat = 400 let E: CGFloat = 20 let dx: Float = 0.25 let graph = CAShapeLayer() override func viewDidLoad() { super.viewDidLoad() drawAxis() let slider = UISlider(frame: CGRect(x: 0, y: H, width: W, height: 30)) slider.addTarget(self, action: #selector(self.sliderChanged(sender:)), for: UIControl.Event.valueChanged) slider.minimumValue = -Float(W) / Float(2 * E) slider.maximumValue = Float(W) / Float(2 * E) self.view.addSubview(slider) } func drawAxis() { let gline = UIBezierPath() gline.move(to: CGPoint(x: 0, y: H / 2)) gline.addLine(to: CGPoint(x: W, y: H / 2)) gline.move(to: CGPoint(x: W / 2, y: H)) gline.addLine(to: CGPoint(x: W / 2, y: 0)) let axis = CAShapeLayer() axis.strokeColor = UIColor.black.cgColor axis.path = gline.cgPath view.layer.addSublayer(axis) let OLabel = UILabel(frame: CGRect(x: W / 2, y: H / 2, width: 12, height: 12)) OLabel.text = "O" self.view.addSubview(OLabel) } @objc func sliderChanged(sender : UISlider) { graph.removeFromSuperlayer() let line = UIBezierPath() var x: Float = -Float(W) / Float(2 * E) while x < Float(W) / Float(2 * E) { let P = defFunction(with: sender.value, and: x) let P_ = defFunction(with: sender.value, and: x + dx) line.move(to: P); line.addLine(to: P_) x += dx } graph.strokeColor = UIColor.blue.cgColor graph.lineWidth = 1.0 graph.path = line.cgPath view.layer.addSublayer(graph) } func defFunction(with k: Float, and x: Float) -> CGPoint { // def of function // let y = k * x * x return CGPoint(x: W / 2 + CGFloat(x) * E, y: H / 2 - CGFloat(y) * E) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } let viewController = ViewController() viewController.view.backgroundColor = UIColor.white PlaygroundPage.current.liveView = viewController PlaygroundPage.current.needsIndefiniteExecution = true