我正在使用UIImagePickerController
选择要用来拍摄照片的来源。该图片应设置为UIButton
。
我知道您可以通过字符串将UIImage
添加到UIButton
,例如
someButton.setImage(UIImage(named:...))
,但是我需要通过在拍摄照片时创建的变量进行设置。
@IBOutlet weak var addPictureOutlet: UIButton!
func chooseSource() {
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
let kameraAction = UIAlertAction(title: "Kamera",
style: .default) { (action) in
imagePickerController.sourceType = .camera
self.present(imagePickerController, animated: true, completion: nil)
}
let libraryAction = UIAlertAction(title: "Galerie",
style: .default) { (action) in
imagePickerController.sourceType = .photoLibrary
self.present(imagePickerController, animated: true, completion: nil)
}
let cancelAction = UIAlertAction(title: "Cancel",
style: .cancel)
let alert = UIAlertController(title: "Quelle",
message: "Wählen sie eine Quelle für die Klausur.",
preferredStyle: .actionSheet)
alert.addAction(kameraAction)
alert.addAction(libraryAction)
alert.addAction(cancelAction)
self.present(alert, animated: true) {
}
}
@IBAction func addPicture(_ sender: UIButton) {
chooseSource()
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let image1 = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
addPictureOutlet.setImage(image1, for: .normal)
}
}
我已经尝试过了,但是我真的无法弄清楚为什么它不起作用,在编译或运行时没有错误,并且UIImage
的{{1}}没有变化。
答案 0 :(得分:1)
您应该这样使用。您不能在操作中使用功能。
@IBOutlet weak var addPictureOutlet: UIButton!
func chooseSource() {
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
let kameraAction = UIAlertAction(title: "Kamera",
style: .default) { (action) in
imagePickerController.sourceType = .camera
self.present(imagePickerController, animated: true, completion: nil)
}
let libraryAction = UIAlertAction(title: "Galerie",
style: .default) { (action) in
imagePickerController.sourceType = .photoLibrary
self.present(imagePickerController, animated: true, completion: nil)
}
let cancelAction = UIAlertAction(title: "Cancel",
style: .cancel)
let alert = UIAlertController(title: "Quelle",
message: "Wählen sie eine Quelle für die Klausur.",
preferredStyle: .actionSheet)
alert.addAction(kameraAction)
alert.addAction(libraryAction)
alert.addAction(cancelAction)
self.present(alert, animated: true) {
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let image1 = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
addPictureOutlet.setImage(image1, for: .normal)
}
@IBAction func addPicture(_ sender: UIButton) {
chooseSource()
}
答案 1 :(得分:0)
正如您所说的,它不会进入imagePicker方法,似乎您错过了正确运行imagePicker方法的委托
添加UIImagePickerControllerDelegate
并创建一个变量来分配UIImagePickerController var imagePicker = UIImagePickerController()
并设置imagePicker.delegate = self