I have an array with separate UIImages and I am displaying them using an UIImageView, how do I add an identifier to them so that I can switch to the view controller with the specific data related to that image.
Below is the code:
class Orders2ViewController: UIViewController, OrdersBaseCoordinated {
var orderList: [OrderInfo] = [OrderInfo( itemImage: UIImage(named: "printer.jpeg")!, itemSKU: 12567), OrderInfo(itemImage: UIImage(named: "ipad.jpeg")!, itemSKU: 34521), OrderInfo( itemImage: UIImage(named: "hoodie.jpeg")!, itemSKU: 93620)]
lazy var someImageView: UIImageView = {
let theImageView = UIImageView()
let tap = UITapGestureRecognizer(target: self, action: #selector(Orders2ViewController.tappedMe))
theImageView.addGestureRecognizer(tap)
theImageView.isUserInteractionEnabled = true
theImageView.image = orderList[selectedIndex].itemImage
theImageView.translatesAutoresizingMaskIntoConstraints = false
return theImageView
}()
@objc func tappedMe(sender: UITapGestureRecognizer)
{
coordinator?.passImageData(j: )
}
I want to pass an identifier in my tappedMe function to recognize which image was tapped on, I did find other answers on SO that mentioned gesture.view.tag but I don't want to create another view, rather navigate to the next controller with an identifier. Is there a way to do this?
CodePudding user response:
Since UIImageView inherits from UIView, you can use it’s parameter called tag
. In your example you can set theImageView.tag = orderedList[selectedIndex].itemSKU
. Then each time tap was recognized, you can just use this itemSKU
to do move to the next screen.
However it seems that you have only one UIImageView on the screen and you use selectedIndex
to determine which image you need. So you can just do like that:
@objc func tappedMe(sender: UITapGestureRecognizer) {
coordinator?.passImageData(j: orderList[selectedIndex].itemImage)
}
I passed the itemImage
just to show you how it can be done. You can use whatever you need.