ios - swift:如何将本地目录中保存的图像显示到自定义单元格中

标签 ios swift uiimagepickercontroller

我在这里实现了一个自定义单元格:

  var imagePath = ""



 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // Static Cell will be shown in first row
        if indexPath.section == 0 && indexPath.row == 0 {
            let cell: ProfilePictureTableViewCell = (NSBundle.mainBundle().loadNibNamed("ProfilePictureTableViewCell", owner: self, options: nil).first as? ProfilePictureTableViewCell)!

            cell.backgroundColor = ClientConfiguration.primaryUIColor()
            cell.selectionStyle = UITableViewCellSelectionStyle.None
            cell.profilePicture.userInteractionEnabled = true
            let tap = UITapGestureRecognizer(target: self, action: #selector(ProfileTableViewController.ProfilePicTapped))
            tap.numberOfTapsRequired = 1
            cell.profilePicture.addGestureRecognizer(tap)
            if(self.imagePath.length > 0)
            {
            cell.profilePicture.image = UIImage(contentsOfFile: self.imagePath)
            }
            else{
                cell.profilePicture.image = self.setProfilePicture
            }
            return cell
        }

此单元格有一个 UIImageView 作为 profilePicture,单击此 View 我可以更改个人资料图片。这是用来加载图片的:

  func ProfilePicTapped(sender: UITapGestureRecognizer){
    print("Edit Profile Picture Clicked")

    profilePictureImage.allowsEditing = false
    profilePictureImage.sourceType = .PhotoLibrary
    presentViewController(profilePictureImage, animated: false, completion: nil)

}


func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    let url = info[UIImagePickerControllerReferenceURL]
    if let referenceUrl = info[UIImagePickerControllerReferenceURL] as? NSURL, pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {



        ALAssetsLibrary().assetForURL(referenceUrl, resultBlock: { asset in

            let fileName = asset.defaultRepresentation().filename()
            //do whatever with your file name
            let nameModel = DefaultNameModel()

            nameModel.value = fileName

            let referenceUrlToString : String = String(referenceUrl)
            let filePath = "\(NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])/\(fileName)"
            self.imagePath = filePath
            let imageData : NSData = UIImagePNGRepresentation(pickedImage)! as NSData
            imageData.writeToFile(filePath, atomically: true)

            self.setProfilePicture = pickedImage

我已经成功写入我的目录,我什至可以在本地文件夹中找到照片。现在我想将我上传的照片放在具有 UIImageView 作为 profilePicture 的单元格中。我怎样才能做到这一点……?

最佳答案

您可以重新加载您的第一行,但首先使用您的 Controller 声明一个 UIImage? 类型的实例属性,并在 cellForRowAtIndexPath 中分配该 image 实例添加到您的 profileImageView,之后在 didFinishPickingMediaWithInfo 中将所选图像设置为该实例并简单地重新加载您的 tableView 的第一行。

var profileImage: UIImage?

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    // Static Cell will be shown in first row
    if indexPath.section == 0 && indexPath.row == 0 {
        let cell: ProfilePictureTableViewCell = (NSBundle.mainBundle().loadNibNamed("ProfilePictureTableViewCell", owner: self, options: nil).first as? ProfilePictureTableViewCell)!

        //Your other setting code for ProfilePictureTableViewCell

        //Set the image
        cell.profilePicture.image = self.profileImage

        return cell
    }

现在在 didFinishPickingMediaWithInfo 中将图像设置为 profileImage 广告重新加载第一部分的第一行。

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

    if let referenceUrl = info[UIImagePickerControllerReferenceURL] as? NSURL, pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {

            //Code for saving image in document directory

            //Now set the selected image to profileImage and reload the first cell
            self.profileImage = pickedImage 
            let indexPath = NSIndexPath(forRow: 0, inSection: 0)
            self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)

编辑:可以在 viewDidLoadviewDidLoad 中保存imagePath 到NSUserDefaults,然后将图片保存到DocumentDirectory您当前的 Controller 只需使用 UserDefaults 检查 imagePath 是否存在,如果它存在,然后使用它从该路径获取图像并将其分配给 profileImage属性。因此,当您将图像保存在 documentDirectory 中时,首先像这样将图像保存在 userDefault 中。

 let imageData : NSData = UIImagePNGRepresentation(pickedImage)! as NSData
 imageData.writeToFile(filePath, atomically: true)
 //Save path in user defaults
 NSUserDefaults.standardUserDefaults().setObject(filePath, forKey: "profileImagePath")
 NSUserDefaults.standardUserDefaults().synchronize()

现在在 viewDidLoad 中简单地检查路径是否存在与键。

if let path = NSUserDefaults.standardUserDefaults().stringForKey("profileImagePath") {
      self.profileImage = UIImage(contentsOfFile: self.imagePath)
 }

注意:cellForRowAtIndexPath 中,只需使用一行 cell.profilePicture.image = self.profileImage 即可设置图像。

关于ios - swift:如何将本地目录中保存的图像显示到自定义单元格中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41847137/

相关文章:

android - 使用 Phongap 的不同移动设备的背景图像大小

c# - Unity 的 iOS 插件

ios - 二元运算符 '<' 不能。应用于两个 'Any?' 操作数

swift - 更改对象的框架大小后更新自动布局

ios - 通过流播放的音频出现抖动/断断续续

ios - Xcode 7 垂直 ScrollView 问题

swift - 使用 Swift Vapor 3.0 上传文件

objective-c - UIImagePickerController 如何隐藏翻转相机按钮?

ios - 使用 UIImagePickerController 减少内存使用

ios - 在图像选择器 iOS 中调整编辑矩形的大小