简体   繁体   中英

Is there a way to include an image asset that will only be available in previews for SwiftUI?

I'm developing a CocoaPod and I'd like to include images in my target that I can use in SwiftUI previews. I don't want them included in the binary or the pod when I ship it. Is that possible?

If I don't include the asset bundle in the podspec it doesn't seem to appear under my development pods, but I don't want it in the podspec because I don't want to ship the images.

I'm thinking there's perhaps a way to do this by running a custom step after pod install that will copy an asset bundle from the example app to the development pod but I haven't quite figured that out yet.

When you create SwiftUI based project it creates the following group, with Preview-only assets catalog

演示

Target build settings:

演示

Following @Asperi's answer, I wrote the following post_install step for my development pod. Remember to change ${TARGET_NAME} for your target:

post_install do |installer_representation|
  project = installer_representation.pods_project
  subdir = "PreviewAssets"
  # First add the PreviewAssets folder to the build settings for the debug configuration
  project.targets.each do |target|
    if target.name == "${TARGET_NAME}"
      target.build_configurations.each do |config|
        if config.name == 'Debug'
          config.build_settings['DEVELOPMENT_ASSET_PATHS'] ||= ['${PODS_TARGET_SRCROOT}/' + subdir]
        end
      end
    end
  end
  # Second grab all the xcassets from the PreviewAssets folder and add them to the ${TARGET_NAME} group in
  # the Development Pods group
  group = project.pod_group("${TARGET_NAME}")
  references = []
  # Is there a better way to get the root of your project?
  directory = installer_representation.sandbox.root.join("../..", subdir)
  Dir.chdir(directory)
  Dir.glob("*").each do |f|
    if File.directory?(f)
      full_path = File.expand_path(f)
      references << project.add_file_reference(full_path, group)
    end
  end
  # Last add the asset catalogs to the target
  project.targets.each do |target|
    if target.name == "${TARGET_NAME}"
      target.add_file_references(references)
    end
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM