Доступ к библиотеке изображений в стиле ActionSheet
Я пытаюсь создать profilePic в контроллере представления регистрации. ProfilePic имеет тип UIImageView. Я хочу иметь возможность прикоснуться к нему, чтобы он мгновенно использовал библиотеку фотографий в стиле ActionSheet. А также иметь на одном из полей изображения кнопку для доступа к камере. Это возможно?
import UIKit
class SignUpViewController: UIViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var profilePic: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// PROFILE PICTURE
let tapGesture = UITapGestureRecognizer(target: self, action: "imageTapped:")
profilePic.addGestureRecognizer(tapGesture)
profilePic.userInteractionEnabled = true
}
func imageTapped(gesture:UIGestureRecognizer) {
if let profile1Pic = gesture.view as? UIImageView {
print("Image Tapped")
}
}
4 ответа
Попробуйте этот код ниже:
import UIKit
class SignUpViewController: UIViewController, UIImagePickerControllerDelegate {
@IBOutlet weak var profilePic: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: "imageTapped:")
profilePic.addGestureRecognizer(tapGesture)
profilePic.userInteractionEnabled = true
}
func imageTapped(gesture:UIGestureRecognizer) {
if let profile1Pic = gesture.view as? UIImageView {
print("Image Tapped")
showActionSheet()
}
}
func camera()
{
var myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.Camera
self.presentViewController(myPickerController, animated: true, completion: nil)
}
func photoLibrary()
{
var myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(myPickerController, animated: true, completion: nil)
}
func showActionSheet() {
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
actionSheet.addAction(UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default, handler: { (alert:UIAlertAction!) -> Void in
self.camera()
}))
actionSheet.addAction(UIAlertAction(title: "Gallery", style: UIAlertActionStyle.Default, handler: { (alert:UIAlertAction!) -> Void in
self.photoLibrary()
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(actionSheet, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
profilePic.image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.dismissViewControllerAnimated(true, completion: nil)
}
}
Это работает на моей стороне.. надеюсь, что сделаю некоторые для вас!
Недавно я опубликовал GitHub-репозиторий для обработки этого типа Action Sheet.
Вы можете скачать этот класс здесь: MSActionSheet
и просто напиши:
РЕДАКТИРОВАТЬ:
● теперь поддерживает iPad
MSActionSheet(viewController: self, sourceView: sender).showFullActionSheet {
sender.setImage($0, for: .normal)
}
MSActionSheet: лучшая библиотека для установки картинки профиля пользователя.
- Я использовал эту библиотеку, но она не поддерживается в iPad, поэтому я настроил некоторые функции для поддержки iPad и Display с помощьюpopOverController.
Ниже шаг настройки.
Заменить функцию на
showFullActionSheet
func showFullActionSheet(on vc : UIViewController, over btn : UIButton,handler : @escaping (_ : UIImage?) -> Void) { let sheet = create().addLibrary().addFrontCamera().addRearCamera().addCancelButton() sheet.show(on: vc,over: btn){ (image : UIImage?) in handler(image) } }
Добавить код перед
vc.present(MSActionSheet.sheet!, animated: true, completion: nil)
в функцииshow
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad { if let presenter = MSActionSheet.sheet?.popoverPresentationController { presenter.sourceView = btn presenter.sourceRect = btn.bounds } }
Добавьте ниже код перед
clientVC?.present(picker, animated: true, completion: nil)
в функцииhandler
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad { picker.modalPresentationStyle = .popover if let presenter = picker.popoverPresentationController { presenter.sourceView = sourceBtn presenter.sourceRect = sourceBtn!.bounds } }
Как пользоваться
let msActionSheet = MSActionSheet.instance msActionSheet.showFullActionSheet(on: self,over: btn){ (image) in btn.setImage(image, for: .normal) } msActionSheet.tintColor(color: Constants.kColorBluish)
Свифт 3х:
class yourClassName:UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
@IBAction func yourButtonName(_ sender: UIButton) {
let pickerView = UIImagePickerController()
pickerView.delegate = self
pickerView.allowsEditing = true
let actionSheetControllerIOS8: UIAlertController = UIAlertController(title: "Please select", message: nil, preferredStyle: .actionSheet)
let cancelActionButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
print("Cancel") //Cancel
}
actionSheetControllerIOS8.addAction(cancelActionButton)
let saveActionButton: UIAlertAction = UIAlertAction(title: "Take Photo", style: .default) { action -> Void in
print("Take Photo") //Will open Camera
if UIImagePickerController.isSourceTypeAvailable(.camera) {
pickerView.sourceType = .camera
self.present(pickerView, animated: true, completion: { _ in })
}
}
actionSheetControllerIOS8.addAction(saveActionButton)
let deleteActionButton: UIAlertAction = UIAlertAction(title: "Camera Roll", style: .default) { action -> Void in
print("Camera Roll") //Will open Gallery
pickerView.sourceType = .photoLibrary
self.present(pickerView, animated: true, completion: { _ in })
}
actionSheetControllerIOS8.addAction(deleteActionButton)
let deleteActionButton2: UIAlertAction = UIAlertAction(title: "Import from Facebook", style: .default) { action -> Void in
print("Import from Facebook")
}
actionSheetControllerIOS8.addAction(deleteActionButton2)
self.present(actionSheetControllerIOS8, animated: true, completion: nil)
}
// MARK: - UIImagePickerControllerDelegate Methods
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//print(info)
if let pickedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
//print(pickedImage)
yourImageView.contentMode = .scaleAspectFit
yourImageView.image = pickedImage
}
dismiss(animated: true, completion: nil)
}
}