2015-03-03 126 views
0

我有一个包含约30个图像图标的文件夹。我试图让用户选择30个“本地”图像之一作为他们的个人资料图片。我期望找到最好的方法来做到这一点,但大多数教程都是为了访问相机胶卷并允许用户上传他们的照片。允许用户在应用程序中选择本地图像Swift

我正在寻找一种方法,也许是一个UICollectionView,并允许他们选择一个图像,将成为用户图标。我了解如何从iPhone本身提取图像,但我正在使用的服务器目前没有进行编码以允许此过程发生。

什么是最好的方式来使用应用程序内的图像,并允许他们被放置到图像视图?

回答

0

UICollectionView是要走的路。

您需要先载入所有本地头像文件名。以下示例将加载以avatar-开头的app目录中的所有图像,忽略所有保留@2x.png文件。

func getAvatarFilenames() -> Array<String> { 
    var avatarFileNames = Array<String>() 
    var paths = NSBundle.mainBundle().pathsForResourcesOfType("png", inDirectory: nil) 
    for path in paths { 
     var imageName = path.lastPathComponent 

     // ignore retina images as when the uiimage loads them back out 
     // it will pick the retina version if required 
     if (imageName.hasSuffix("@2x.png")) { 
      continue 
     } 

     // only add images that are prefixed with 'avatar-' 
     if (imageName.hasPrefix("avatar-")) { 
      avatarFileNames.append(imageName) 
     } 
    } 

    return avatarFileNames 
} 

然后,您可以创建一个加载每个头像文件名的UICollectionView。像这样配置每个单元格(假设您的AvatarCell具有标签1000的图像 - 或更好,UICollectionViewCell子类)。

var cell = collectionView.dequeueReusableCellWithReuseIdentifier("AvatarCell", forIndexPath: indexPath) as UICollectionViewCell 
var avatarImageView = cell.viewWithTag(1000) as UIImageView 
avatarImageView.image = UIImage(named: avatarFileNames[indexPath.row]) 
相关问题