Swift Playgrounds with Uiimage

Swift playgrounds with UIImage


  1. Open the .playground file in Finder.
  2. Create a folder called Resources next to it.
  3. Add any images you want to this folder.
  4. In the playground press opt-cmd-1 to open the File Inspector. You should see the playground on the right. If you don't have it selected, press cmd-1 to open the Project Navigator and click on the playground file.

File Inspector


  1. Under 'Resource Path' choose 'Relative To Playground'
  2. Click the folder icon underneath and choose the Resources folder created earlier.

You should now have a bundle that you can use with the standard NSImage(named:"filename_without_extension"):

Working nsbundle image

Note: Because Xcode will frequently overwrite the .playground folder, I recommend using this method so the resources folder isn't getting constantly deleted and re-created.

How to use Image() in Swift Playgrounds for IPad

The following is what I did and worked for the iPad:

import SwiftUI

extension Image {
// usage: Image(name: "imageNameHere.jpg")
public init(name:String) {
self.init(uiImage: #imageLiteral(resourceName: name))
}
}

or

extension Image {
// usage: Image(name: "imageNameHere.jpg")
public init(name: String) {
self.init(uiImage: UIImage(named: name)!)
}
}

PS: Don't forget to import your image into Swift Playgrounds for iPad first.

Swift Playground add a WORKING image view

You drag it into the Resources folder, then access it from the Bundle. Sample code:

//: A UIKit based Playground for presenting user interface

import UIKit
import PlaygroundSupport

let view = UIView(frame: CGRect(x: 0, y: 0, width: 916, height: 611))
view.backgroundColor = .white
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 916, height: 611))
view.addSubview(imageView)


if let sample = Bundle.main.path(forResource: "sample", ofType: "jpg") {
let image = UIImage(contentsOfFile: sample)
imageView.image = image
}

PlaygroundPage.current.liveView = view
PlaygroundPage.current.liveView

Here's the result:

playground result



Related Topics



Leave a reply



Submit