ios - 无法在同一视图控制器上触发 2 个图像的点击手势标识符
问题描述
我在我的视图控制器中为我的 2 个图像分配了 2 个不同的点击手势标识符。我想在点击时访问并分配不同的图像。我编写了以下代码,它仅适用于一个图像。但是,我不确定如何将它分配给两个不同的图像。我什至为这两个图像分配了不同的标签,但不知道如何使用它们。任何帮助将不胜感激!谢谢!
import UIKit
class EleventhViewController: UIViewController {
@IBOutlet weak var person1ImageView: UIImageView!
@IBOutlet weak var person2ImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
person1ImageView.tag = 1
person2ImageView.tag = 2
}
extension EleventhViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
//This is the tap gesture added on my UIImageView.
@IBAction func didTapOnImageView(sender: UITapGestureRecognizer) {
//call Alert function
self.showAlert()
}
//Show alert to selected the media source type.
private func showAlert() {
let alert = UIAlertController(title: "Image Selection", message: "From where you want to pick this image?", preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: {(action: UIAlertAction) in
self.getImage(fromSourceType: .camera)
}))
alert.addAction(UIAlertAction(title: "Photo Album", style: .default, handler: {(action: UIAlertAction) in
self.getImage(fromSourceType: .photoLibrary)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .destructive, handler: nil))
self.present(alert, animated: true, completion: nil)
}
//get image from source type
private func getImage(fromSourceType sourceType: UIImagePickerController.SourceType) {
//Check is source type available
if UIImagePickerController.isSourceTypeAvailable(sourceType) {
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.sourceType = sourceType
self.present(imagePickerController, animated: true, completion: nil)
}
}
//MARK:- UIImagePickerViewDelegate.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
self.dismiss(animated: true) { [weak self] in
guard let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else { return }
//Setting image to your image view
self?.person2ImageView.image = image
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
}
解决方案
您必须UITapGestureRecognizer
为每个 imageView 创建一个对象并添加它,如果您将相同的 1 添加到两个图像,它将仅触发最后一个 1
var last = 0
@objc func didTapOnImageView(sender: UITapGestureRecognizer) {
last = sender.view!.tag
}
推荐阅读
- php - 在 laravel 中创建考勤报告
- node.js - 如果在返回多个承诺时放在底部,Firestore 将不会写入文档
- c++ - C ++:从其他类访问结构的私有成员向量
- ruby-on-rails - Rails DelayedJob run_at 时区差异
- micro-frontend - 从 single-spa 框架(用于微前端应用程序的框架)调用 start 方法后,我可以懒惰地注册微前端吗?
- python - 用于自动在线工具查询的脚本
- c# - 为什么推荐的 dispose 模式会在层次结构的每个级别添加一个已处理字段?
- sql - 更新多行并从另一个表插入新行
- javascript - 在 jQuery 中添加或删除类
- python - KeyError 熊猫数据框