目錄:[Swift]Xcode實際操做html
本文將演示從系統相冊中讀取圖片。swift
在項目導航區,打開視圖控制器的代碼文件【ViewController.swift】ide
1 import UIKit 2 3 //添加兩個協議:UIImagePickerControllerDelegate, UINavigationControllerDelegate 4 //來實現加載和讀取相冊的功能 5 class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { 6 7 //添加一個圖像視圖屬性,用來顯示從相冊中讀取的照片 8 var imageView: UIImageView! 9 //添加一個圖片拾取控制器,做爲當前視圖控制器的屬性 10 var imagePickerController: UIImagePickerController! 11 12 override func viewDidLoad() { 13 super.viewDidLoad() 14 // Do any additional setup after loading the view, typically from a nib. 15 16 //初始化圖像視圖,並設置其位置在(20,120),尺寸爲(280,200)。 17 self.imageView = UIImageView(frame: CGRect(x: 20, y: 120, width: 280, height: 200)) 18 //而後將圖像視圖,添加到當前視圖控制器的根視圖。 19 self.view.addSubview(imageView) 20 21 //建立一個按鈕控件,並設置其位置在(20,60),尺寸爲(280,40) 22 let button = UIButton(frame: CGRect(x: 20, y: 60, width: 280, height: 40)) 23 //同時設置按鈕在正常狀態下的標題文字。 24 button.setTitle("選擇一張圖片", for: .normal) 25 //而後給按鈕綁定點擊事件 26 button.addTarget(self, action: #selector(ViewController.pickImage), for: UIControl.Event.touchUpInside) 27 //設置按鈕的背景顏色爲深灰色 28 button.backgroundColor = UIColor.darkGray 29 30 //一樣將按鈕,添加到當前視圖控制器的根視圖 31 self.view.addSubview(button) 32 } 33 34 //添加一個方法,用來響應按鈕的點擊事件 35 @objc func pickImage() 36 { 37 //初始化圖片拾取控制器對象 38 self.imagePickerController = UIImagePickerController() 39 //設置圖片拾取控制器的代理對象,爲當前的視圖控制器 40 self.imagePickerController.delegate = self 41 //設置圖片拾取控制器,是否容許用戶移動、縮放和剪切圖片 42 self.imagePickerController.allowsEditing = false 43 //設置圖片拾取控制器的來源類型爲系統相冊 44 self.imagePickerController.sourceType = UIImagePickerController.SourceType.photoLibrary 45 //設置圖片拾取控制器導航條的前景色爲橙色 46 self.imagePickerController.navigationBar.barTintColor = UIColor.orange 47 //設置圖片拾取控制器的着色顏色爲白色 48 self.imagePickerController.navigationBar.tintColor = UIColor.white 49 //最後在當前視圖控制器窗口,展現圖片拾取控制器。 50 self.present(self.imagePickerController, animated: true, completion: nil) 51 } 52 53 //添加一個代理方法,用來響應完成圖片拾取的事件 54 func imagePickerController(_ picker: UIImagePickerController, 55 didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { 56 57 //在控制檯打印輸出得到的數據媒體類型 58 print(info[UIImagePickerController.InfoKey.mediaType] ?? "") 59 //在控制檯打印輸出得到的參考路徑 60 print(info[UIImagePickerController.InfoKey.referenceURL] ?? "") 61 //將用戶選擇的圖片,賦予圖像視圖 62 self.imageView.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage 63 //而後取消圖片拾取控制器的展現 64 self.dismiss(animated: true, completion: nil) 65 } 66 67 //添加一個代理方法,用來響應用戶取消圖片拾取的事件 68 func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { 69 //當用戶取消圖片拾取時,隱藏圖片拾取控制器 70 self.dismiss(animated: true, completion: nil) 71 } 72 73 override func didReceiveMemoryWarning() { 74 super.didReceiveMemoryWarning() 75 // Dispose of any resources that can be recreated. 76 } 77 }