C. Pave C. Pave - 6 months ago 17
Swift Question

Delegate's function returns nil

I followed a delegation tutorial in Objective C quite grasped the concept, and then try to implement it in swift.

I have a custom view inheriting "AppController" class, and a NSObject inheriting "SquareView" class.

AppContoller.swift

import Cocoa

class AppController: NSObject,SquareViewDelegate {
var squareCount:Int = 10

@IBOutlet var squareView: SquareView!

override func awakeFromNib() {
squareView.needsDisplay = true
}

@IBAction func changeSquareCount(sender:AnyObject) {
squareCount = Int(sender.intValue)
squareView.needsDisplay = true
}

func numberOfSquaresInQuareView(squareView: SquareView) -> Int {
return squareCount
}
}


SquareView.swift

import Cocoa
import Foundation

protocol SquareViewDelegate {
func numberOfSquaresInQuareView(squareView:SquareView)->Int
}

class SquareView: NSView {

var delegate: SquareViewDelegate!

override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
}

required init?(coder: NSCoder) {
super.init(coder: coder)
}

override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
NSColor.redColor().set()
let num: Int = delegate.numberOfSquaresInQuareView(self)
for _ in 0..<num {
let x:CGFloat = CGFloat(arc4random()) % CGFloat(self.frame.size.width - 20)
let y:CGFloat = CGFloat(arc4random()) % CGFloat(self.frame.size.width - 20)
NSRectFill(NSMakeRect(x, y, 10, 10))
}
}
}


When I build and run, my delegate.numberOfSquaresInSquareView returns nil.
I feel like I haven't linked the delegate properly but I don't know how.

(I'm sorry, I know many people have ask this question already, but their answers still confuse me.)

Answer

You didn't set your AppController to be the SquareView delegate, so it won't be called.

Try with the code below, it should work.

override func awakeFromNib() {
    squareView.needsDisplay = true
    squareView.delegate = self
}
Comments