Swift 3: Drawing a rectangle

In order to see the view, you need to create one and give it frame so that it knows how big to make it.

If you put your code in a Playground, and then add this line:

let d = Draw(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

You'll be able to click on the Quick View on the right, and then you'll see the view.

Yellow square in a playground


You can also add the view as a subview of view in your ViewController and then you'll see it on the iPhone:

override func viewDidLoad() {
    super.viewDidLoad()

    let k = Draw(frame: CGRect(
        origin: CGPoint(x: 50, y: 50),
        size: CGSize(width: 100, height: 100)))

    // Add the view to the view hierarchy so that it shows up on screen
    self.view.addSubview(k)
}

Note that you never call draw(_:) directly. It is called for you by Cocoa Touch to display the view.

Yellow square on iPhoneSE


Create a class, I put it in a separate Swift 3 file.

//
//  Plot_Demo.swift
//
//  Storyboard is not good in creating self adapting UI
//  Plot_Demo creates the drawing programatically.

import Foundation
import UIKit

public class Plot_Demo: UIView
{
    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    public override func draw(_ frame: CGRect) {
        let h = frame.height
        let w = frame.width
        let color:UIColor = UIColor.yellow

        let drect = CGRect(x: (w * 0.25), y: (h * 0.25), width: (w * 0.5), height: (h * 0.5))
        let bpath:UIBezierPath = UIBezierPath(rect: drect)

        color.set()
        bpath.stroke()

        print("it ran")
        NSLog("drawRect has updated the view")
    }
}

Example of use in an UIViewController object:

override func viewDidLoad() {
    super.viewDidLoad()

    // Instantiate a new Plot_Demo object (inherits and has all properties of UIView)
    let k = Plot_Demo(frame: CGRect(x: 75, y: 75, width: 150, height: 150))

    // Put the rectangle in the canvas in this new object
    k.draw(CGRect(x: 50, y: 50, width: 100, height: 100))

    // view: UIView was created earlier using StoryBoard
    // Display the contents (our rectangle) by attaching it
    self.view.addSubview(k)
}

Run in an iPhone simulator and on an iPhone:

enter image description here

Used XCode Version 8.0 (8A218a), Swift 3, target iOS 10.0