长按

时间:2015-09-18 08:40:24

标签: ios swift uiimageview uiimage

我有一个用于共享和保存图像的iOS Swift项目。我尝试添加长按交互以保存图像。我创建了交互功能,但我不知道如何在Swift中保存图像。

我的代码

override func viewDidLoad() {

        super.viewDidLoad()

        let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "longPressed:")
        self.view.addGestureRecognizer(longPressRecognizer)

    }

func longPressed(sender: UILongPressGestureRecognizer) {

        println("longpressed")

    }

我想知道如何在图片库中添加图片。提前感谢您的回复。

2 个答案:

答案 0 :(得分:4)

使用此代码

import UIKit

class ViewController: UIViewController {

    @IBOutlet var imageview: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        imageview.userInteractionEnabled = true
        let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "longPressed:")
        longPressRecognizer.minimumPressDuration = 0.5
        imageview.addGestureRecognizer(longPressRecognizer)

        // Do any additional setup after loading the view, typically from a nib.
    }
    func longPressed(sender: UILongPressGestureRecognizer) {
        UIImageWriteToSavedPhotosAlbum(imageview.image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func image(image: UIImage!, didFinishSavingWithError error: NSError!, contextInfo: AnyObject!) {
        if (error != nil) {
            // Something wrong happened.
        } else {
            // Everything is alright.
        }
    }

}

答案 1 :(得分:0)

试试这个,你应该编辑你的问题,以保存UICollectionViewCell中显示的图像

class ViewController: UIViewController {
    @IBOutlet weak var collectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "longPressed:")
        collectionView.addGestureRecognizer(longPressRecognizer)
    }

    func longPressed(sender: UILongPressGestureRecognizer) {
        if (sender.state != .Ended) {
            return
        }
        let point = sender.locationInView(self.collectionView)
        let indexPath = self.collectionView.indexPathForItemAtPoint(point)

        if (indexPath == nil) {
            print("long press on collection view but not on a item")
        } else {
            let cell = self.collectionView.cellForItemAtIndexPath(indexPath!)
            // save image to album
            UIImageWriteToSavedPhotosAlbum(cell.imageView.image!, self, "image:didFinishSavingWithError:contextInfo:", nil)
        }
    }

    func image(image: UIImage!, didFinishSavingWithError error: NSError!, contextInfo: AnyObject!) {
        if (error != nil) {
            // Something wrong happened.
            print(error.localizedDescription)
        } else {
            // Everything is alright.
        }
    }
}