swiftgraphicsdrawdrawrectswift3

Swift 3: Drawing a rectangle


I'm 3 days new to swift, and I'm trying to figure out how to draw a rectangle. I'm too new to the language to know the classes to extend and the methods to override, and I've looked around for sample code, but nothing seems to work (which I'm attributing to my use of swift 3).

What I'm trying now is:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()


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

        k.draw(CGRect(
            origin: CGPoint(x: 50, y: 50),
            size: CGSize(width: 100, height: 100)));
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}
class Draw: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

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

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

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

        color.set()
        bpath.stroke()

        print("it ran")

        NSLog("drawRect has updated the view")

    }

}

And that's not doing anything. Help.


Solution

  • 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