iOS開發——儲存圖片到相簿&Swift+OC篇

來源:互聯網
上載者:User

標籤:

儲存圖片到相簿1.OC中的寫法

在OC中,我們需要儲存圖片到相簿需要調用這個方法:

void UIImageWriteToSavedPhotosAlbum(UIImage *image, id completionTarget, SEL completionSelector, void *contextInfo);

想來大家也都看過這個方法的標頭檔,在標頭檔中有這樣一段話

// Adds a photo to the saved photos album.  The optional completionSelector should have the form://  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;

意思是:想要將一張照片儲存到相簿中,這個可選的完成方法需要按照下面那個方法的格式來定義。 
所以,我們在OC中通常都是直接將這個方法拷貝出來,直接實現這個方法,舉個栗子:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {    UIImageWriteToSavedPhotosAlbum(self.iconView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);}- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {    if (error) {        NSLog(@"儲存出錯");        return;    }    NSLog(@"儲存成功");}

在上面這個栗子中,我通過手指觸摸事件,將事先定義好的iconView中的映像儲存到相簿中。

而同樣一個栗子,在Swift中應該怎麼樣實現呢?

2.swift中的寫法
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {    UIImageWriteToSavedPhotosAlbum(iconView.image, self, "image:didFinishSavingWithError:contextInfo:", nil)}    func image(image: UIImage, didFinishSavingWithError: NSError?, contextInfo: AnyObject) {    println("---")    if didFinishSavingWithError != nil {        println("錯誤")        return    }    println("OK")}

同樣的栗子,swift中的實現如上,在swift中,我們跳到標頭檔會發現是這樣的,

// Adds a photo to the saved photos album.  The optional completionSelector should have the form://  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;

還是OC中那一套,蘋果並沒有幫我們寫好swift下的代碼格式應該怎麼寫,所以很多人對此應該怎麼使用會產生許多的疑惑,其實,就是像上面那樣,將參數一一對應,以swift中函數的寫法寫出來就可以了。 
另外補充一點小知識點: 
上面的那個方法我們還可以這麼寫,

    // 提示:參數 空格 參數別名: 類型func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {    println("---")//        if didFinishSavingWithError != nil {    if error != nil {        println("錯誤")        return    }    println("OK")}

類似這樣的格式:(參數 參數別名: 類型)didFinishSavingWithError error: NSError? 
在外部調用時,顯示的是didFinishSavingWithError這個參數名 
而在內部使用時,顯示的是error這個參數別名,方便我們的使用,也更加類似OC中的寫法。

  

iOS開發——儲存圖片到相簿&Swift+OC篇

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.