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

时间:2017-01-25 08:53:23

标签: 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,点击此视图后我可以更改个人资料图片。这用于加载图片:

  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的单元格中。我怎样才能实现这个目标..?

2 个答案:

答案 0 :(得分:1)

您可以重新加载第一行,但为此,首先使用您的控制器声明一个类型为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)

修改:您可以将{/ 1}}中的imagePath保存在NSUserDefaults中,然后在当前控制器的DocumentDirectory上保存,只需检查{{1}如果存在,则存在viewDidLoad,然后使用它从该路径获取图像并将其分配给imagePath属性。因此,当您在documentDirectory中保存图像时,首先将图像保存在userDefault中。

UserDefaults

现在在viewDidLoad中,只需检查该路径是否存在。

profileImage

注意:只需使用单行 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() if let path = NSUserDefaults.standardUserDefaults().stringForKey("profileImagePath") { self.profileImage = UIImage(contentsOfFile: self.imagePath) } 设置图片。

答案 1 :(得分:1)

您可以使用以下方法配置单元格:

func configureCell ( cell : ProfilePictureTableViewCell, imageName : String){

    let path: String? = Bundle.main.path(forResource: imageName, ofType: "png", inDirectory: "DirectoryName/Images")
    let imageAtPath = UIImage(contentsOfFile: path!)!
    cell.imageView?.image = imageAtPath
}

在这里," ProfilePictureTableViewCell"是示例UITableView自定义单元格。

从以下方式调用此方法:

 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)!


    configureCell(cell: cell, imageName: "Pass Image Name") // You can change the paramets to the function as per your requirement

    return cell
}