New to Swift OSX: NSImageView Drawing multiple images with drawInRect - Can't update image

686 views Asked by At

Please forgive my ignorance.. I'm new to Swift and I'm trying to sort this out..

I have a custom NSImageView (called 'AdFrame') that draws two images within NSRects. I want the bottom image to change when a user inputs a certain number.

It draws fine when loading the default image (upon starting the app), but won't update with the new image

Here is the function (drawImages) in the NSImageView class:

    var adUrl = NSURL(string: "ftp://mysite.com/12345.jpg")

    let topImage = NSImage(named: "logo")
    let bottomImage = NSImage(byReferencingURL: adUrl!)

    let bottomRect = NSRect.init(x: 0, y: 0, width: 500, height: 200)
    let topRect = NSRect.init(x: 250, y: 250, width: 100, height: 75)

    adImage.drawInRect(bottomRect)
    logoImage!.drawInRect(topRect)

The function to update the bottom image, from another class:

@IBAction func updateImage(sender: AnyObject) {
    let theADFrame = AdFrame()
    let adNumber = adNumTF.stringValue
    theADFrame.adUrl = NSURL(string: "ftp://mysite.com/\(adNumber).jpg")
    theADFrame.drawImages()
 }

When running this function, the new url is being passed to the ImageView, but the images aren't updating in my app.

Thanks

1

There are 1 answers

1
vadian On

drawImages uses always the same URL (12345). You might pass the URL to drawImages as a parameter.

func drawImages(url : NSURL) {

    let topImage = NSImage(named: "logo")
    let bottomImage = NSImage(byReferencingURL: url)

    let bottomRect = NSRect.init(x: 0, y: 0, width: 500, height: 200)
    let topRect = NSRect.init(x: 250, y: 250, width: 100, height: 75)

    adImage.drawInRect(bottomRect)
    logoImage!.drawInRect(topRect)
}

and call it in updateImage

let adUrl = NSURL(string: "ftp://mysite.com/\(adNumber).jpg")!
theADFrame.adUrl = adUrl
theADFrame.drawImages(adUrl)

and the first call

drawImages(NSURL(string: "ftp://mysite.com/12345.jpg")!)