在plist中存储图像路径然后检索以在屏幕上显示

时间:2016-03-19 16:58:50

标签: xcode swift plist property-list

我正在尝试制作一个应用程序,其中图片中出现了一个单词的字谜。我有anagram部分,但我无法得到图片。图片保存在名为“images”的文件夹中。我想调用anagramPics - 项目0,同时作为anagrams -item 0 - 将该单词与pic匹配

提前致谢。

I would like to call anagramPics - item 0, at the same time as anagrams -item 0 - to match the word with the pic

anagram的代码:

level.m

#import "Level.h"

@implementation Level

+(instancetype)levelWithNum:(int)levelNum;
{
 // find .plist file for this level
  NSString* fileName = [NSString stringWithFormat:@"level%i.plist", levelNum];
  NSString* levelPath = [[[NSBundle mainBundle] resourcePath]      stringByAppendingPathComponent:fileName];

  // load .plist file
  NSDictionary* levelDict = [NSDictionary dictionaryWithContentsOfFile:levelPath];

  // validation
  NSAssert(levelDict, @"level config file not found");

  // create Level instance
  Level* l = [[Level alloc] init];

  // initialize the object from the dictionary
  l.pointsPerTile = [levelDict[@"pointsPerTile"] intValue];
  l.anagrams = levelDict[@"anagrams"];
  l.timeToSolve = [levelDict[@"timeToSolve"] intValue];

  return l;
}

@end

level.h

#import <Foundation/Foundation.h>

@interface Level : NSObject

//properties stored in a .plist file
@property (assign, nonatomic) int pointsPerTile;
@property (assign, nonatomic) int timeToSolve;
@property (strong, nonatomic) NSArray* anagrams;

//factory method to load a .plist file and initialize the model
+(instancetype)levelWithNum:(int)levelNum;

@end

gameController.h

-(void)dealRandomAnagram
{
//1
NSAssert(self.level.anagrams, @"no level loaded");

//2 random anagram
int randomIndex = arc4random()%[self.level.anagrams count];
NSArray* anaPair = self.level.anagrams[ randomIndex ];

//3
NSString* anagram1 = anaPair[0];
NSString* anagram2 = anaPair[1];

//4
int ana1len = [anagram1 length];
int ana2len = [anagram2 length];

//5
NSLog(@"phrase1[%i]: %@", ana1len, anagram1);
NSLog(@"phrase2[%i]: %@", ana2len, anagram2);    
}

1 个答案:

答案 0 :(得分:0)

我有类似的情况,我有一些固定的图像要显示。这就是我所做的。

在Storyboard上添加了UIImageView。使用约束等将它定位在我想要的位置。

为它创建了一个IBOutlet。称之为myImageView。

我将所有图片添加为资源。在我的情况下,我显示各种信用卡图像,但原理是相同的。

Click on Images.xcassets

Credit card image assets

Looks like this in Xcode

每个图片资源都是一个包含Contents.json文件的文件夹,以及随附的图像文件。您会注意到有三个文件。 iOS将为视网膜,iPhone 6plus等使用正确尺寸的图像。

Contents.json看起来像这样:

{
    "images" : [
        {
            "idiom" : "universal",
            "scale" : "1x",
            "filename" : "card-visa@1x.png"
        },
        {
            "idiom" : "universal",
            "scale" : "2x",
            "filename" : "card-visa@2x.png"
        },
        {
            "idiom" : "universal",
            "scale" : "3x",
            "filename" : "card-visa@3x.png"
        }
    ],
    "info" : {
        "version" : 1,
        "author" : "xcode"
    }
}

asset folder

在代码中,通过设置其image属性来更改UIViewImage的图像。

(这是Swift代码。你必须自己将它转换为Objective-C。)

myImageView.image = UIImage(named:"Card VISA")