UIImagePickerControllerDelegate到Swift?

时间:2014-06-03 03:48:56

标签: ios objective-c uiimagepickercontroller swift

    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
    {

        var imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.Camera;
        //imagePicker.mediaTypes = kUTTypeImage
        imagePicker.allowsEditing = false

        self.presentViewController(imagePicker, animated: true, completion: nil)

    }

我似乎无法将kUTTypeImage转换为swift,如果我注释掉这一行,相机会启动,但屏幕是黑色的。有任何想法吗?这是客观的C语法:

imagePicker.mediaTypes = @[(NSString *) kUTTypeImage];

5 个答案:

答案 0 :(得分:3)

显然这很简单:

if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
{
    var imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = UIImagePickerControllerSourceType.Camera;
    imagePicker.mediaTypes = [kUTTypeImage]
    imagePicker.allowsEditing = false

    self.presentViewController(imagePicker, animated: true, completion: nil)
}

答案 1 :(得分:2)

我在XCode6 beta5中测试了这些代码,发现以下错误:

  

致命错误:数组元素无法桥接到Objective-C

     

线程1:EXC_BREAKPOINT(代码= EXC_ARM_BREAKPOINT,子代码-0xe7ffdefe)

原因是我们无法在XCode6 beta5中将带有对象的数组分配给 imagePicker.mediaTypes

imagePicker.mediaTypes = [kUTTypeImage]

我通过init函数用对象初始化了数组,现在工作正常↓↓↓

imagePicker.mediaTypes = NSArray(object: kUTTypeImage)

答案 2 :(得分:1)

要定义kUTTypeMovie,您可以使用:

imagePicker.mediaTypes = [String(kUTTypeMovie)]

答案 3 :(得分:0)

要添加电影和图片,您可以这样做。

let availableMediaTypes = UIImagePickerController.availableMediaTypesForSourceType(.Camera)
self.imagePickercontroller.mediaTypes = availableMediaTypes!

您会注意到,在显示imagePickercontroller时,您可以导航到视频或捕获图像按钮。接下来只需检查委托方法“didFinishPickingMediaWithInfo”中的mediatype类型

答案 4 :(得分:0)

标记为正确答案的代码在Swift 4+中不再起作用,因为已经进行了一些更改。

UIImagePickerControllerSourceType.Camera更改为UIImagePickerController.SourceType.camera,而self.presentViewController(...)更改为self.present(...)

以下是适用于Swift 4+的相同代码:

if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera)
    {

        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerController.SourceType.camera;
        imagePicker.allowsEditing = false

        self.present(imagePicker, animated: true, completion: nil)

    }