How to allow user to pick the image with Swift?

后端 未结 21 866
[愿得一人]
[愿得一人] 2020-12-02 06:01

I am writing my first iOS application (iPhone only) with Swift. The main application view should allow user to choose the image from the photo gallery.

I\'ve found

21条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 06:27

    I will give you best understandable coding for pick the image,refer this

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) 
    {
         var alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
         var cameraAction = UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default)
         {
            UIAlertAction in
            self.openCamera()
         }
         var gallaryAction = UIAlertAction(title: "Gallary", style: UIAlertActionStyle.Default)
         {
            UIAlertAction in
            self.openGallary()
         }
         var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel)
         {
            UIAlertAction in
         }
    
        // Add the actions
         picker?.delegate = self
         alert.addAction(cameraAction)
         alert.addAction(gallaryAction)
         alert.addAction(cancelAction)
         self.presentViewController(alert, animated: true, completion: nil)
    }
    func openCamera()
    {
        if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera))
        {
            picker!.sourceType = UIImagePickerControllerSourceType.Camera
            self .presentViewController(picker!, animated: true, completion: nil)
        }
        else
        {
            let alertWarning = UIAlertView(title:"Warning", message: "You don't have camera", delegate:nil, cancelButtonTitle:"OK", otherButtonTitles:"")
            alertWarning.show()
        }
    }
    func openGallary()
    {
        picker!.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        self.presentViewController(picker!, animated: true, completion: nil)
    }
    
    //PickerView Delegate Methods
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject])
    {
        picker .dismissViewControllerAnimated(true, completion: nil)
        imageView.image=info[UIImagePickerControllerOriginalImage] as? UIImage
    }
    func imagePickerControllerDidCancel(picker: UIImagePickerController)
    {
        println("picker cancel.")
    }
    

    Have a nice day:-)

提交回复
热议问题