Swift playgrounds with UIImage

前端 未结 11 1841
轻奢々
轻奢々 2020-12-01 01:36

I am working with Xcode 6, and I\'m trying to recreate the code demoed during session 401 \"What\'s new in Xcode 6\". I\'ve added an image to Images.xcassets (called Sample)

相关标签:
11条回答
  • 2020-12-01 02:29

    I had some trouble with this also.

    Unfortunately, Chris' answer didn't work for me. I suspect perhaps a later beta release of Xcode 6 may have removed this setting.

    Here's a solution as of Xcode 6.0 beta 4 (6A267N) available 21st July 2014. I would guess that this corresponds to the "Inside playground" option previously. That is where the Resources folder is within the playground package itself.

    Here's how to set this up.

    Using Finder - or if you're like me and use the awesome Path Finder - right select and choose Show Package Contents as follows:

    enter image description here

    That reveals the packages Resources folder:

    enter image description here

    Copying the image files into that folder will do the business:

    let imageNames = ["back-button", "background", "bg_top"]
    let images = imageNames.map { UIImage(named: $0) }
    

    enter image description here

    0 讨论(0)
  • 2020-12-01 02:32

    You can find out the path of resourcePath using these commands in playground:

    var bundle = NSBundle.mainBundle()
    var path = bundle.resourcePath
    

    Default for me was:

    /Applications/Xcode6-Beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Xcode/Agents
    
    0 讨论(0)
  • 2020-12-01 02:34

    For Xcode 9:

    • Select Resources folder
    • Right click then "Add files to "Resources""
    • Use it like: let image = UIImage(named: "no")

    0 讨论(0)
  • 2020-12-01 02:34

    This is what worked for me on Xcode Version 6.1.1.

    1. Create Playground file under same directory as main storyboard.

      Folder Structure

    2. Open Utilities pane for Playground file, and click the right arrow in Resource Path section to add your images in that directory.

      Resource Path for Playground

    3. Test image within Playground file.

      Result

    0 讨论(0)
  • 2020-12-01 02:39

    I had difficulty getting this setup for an iOS playground, as opposed to an OS X playground. Trying to do it using bundles and relative paths makes it more complicated.

    If you just want to get your hands on an image quickly, you can also just use absolute file path:

    On iOS:

    # iOS
    let absoluteImagePath = "/absolute/path/to/image.png"
    let image = UIImage(contentsOfFile: absoluteImagePath)
    

    And on OS X

    # OS X
    let absoluteImagePath = "/absolute/path/to/image.png"
    let image = NSImage(contentsOfFile: absoluteImagePath)
    
    0 讨论(0)
提交回复
热议问题