Open Xcode and create a new Single View Application. For product name, use IOS8SwiftTakePhotoTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.
打开Xcode并且创建一个新的Single View Application,项目名用IOS8SwiftTakePhotoTutorial,然后根据你的习惯填写Organization Name 和Organization Identifier,选择swift语言,确认之选中iPhone这个设备
Go to the Storyboard and drag an Image View from the Object Library to the main view. Go to the Size inspector and enter the following values.
去Storyboard从Object Library 拖拽一个Image View到主视图上,设置尺寸和值
Drag a Button from the Object Library to the main view and place it below the Image View. Give the button a title of "Take Photo".
从Object Librar拖拽一个Button到主视图上,将它放在the Image之下,设置button的title为"Take Photo".
Select the Assistant Editor and make sure the ViewController.swift is visible. Ctrl and drag from the Image to the ViewController class and create the following Outlet.
选择的Assistant编辑,确保viewcontroller.swift是可见的。Ctrl键并拖动Image到 ViewController
这个类,用Outlet创建
Ctrl an drag from the Button to the ViewController class and create the following Action
Ctrl键并拖动Button到 ViewController 这个类,用Action创建
Go to the ViewController.swift file and create the following property
去ViewController.swift这个类里声明它们的属性
var imagePicker: UIImagePickerController!
Change the class declaration line to.
实现类的声明
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
The ViewController now needs to conform to the UINavigationControllerDelegate and UIImagePickerControllerDelegate protocol. Next, implement the takePhoto IBAction method
ViewController现在需要遵循uinavigationcontrollerdelegate和uiimagepickercontrollerdelegate协议。其次,实现action拍照的方法
@IBAction func takePhoto(sender: UIButton) { imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = .Camera presentViewController(imagePicker, animated: true, completion: nil) }
The Image Picker Controller is initialized with a source type of Camera and it will be presented. Next, implement the UIImagePickerController delegate method imagePickerController(picker:didFinishMediaWithInfo)
图像选择器控制器初始化源类型的摄像机。其次,实现uiimagepickercontroller代理方法imagepickercontroller(picker::didfinishmediawithinfo)
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { imagePicker.dismissViewControllerAnimated(true, completion: nil) imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage }
The Image Controller is dismissed and the photo is assigned to the Image View. The info parameter is a dictionary containing the original image. Build and Run the project and grant access to the built-in camera.
图像控制器被销毁,照片展示到 Image View。信息参数是一个包含原始图像的字典Build
and Run 该项目并设置内置摄像机的访问权限。
Select "Take Photo" and take a photo. Choose "Use Photo" to display the photo inside the Image View.
点击按钮拍照,选择使用照片,将照片展示
请发表评论