在我的故事板中,我有一些“启用了用户交互”的图像。在UIViewController中,我覆盖了touchesEnded函数。
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
}是否可以获取在此函数中单击的图像的名称?我不喜欢@IBOutlet的图像。
发布于 2017-08-30 20:15:49
我非常确定这不可能完全像你想要的那样。图像视图不保留从中加载图像的文件,只保留图像数据本身。但我假设您在IB中设置图像名称,并在触摸事件后尝试获取该名称,在这种情况下,您可以在元素的恢复ID中设置图像名称,并通过被触摸元素的restorationIdentifier属性检索名称。
你可以像这样得到被触摸的元素:
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch: UITouch = touches.first {
let location = touch.location(in: self.view)
let touchedView = self.view.hitTest(location, with: event)
print(touchedView.restorationIdentifier)
}
}请注意,如果您想这样做,您必须设置图像文件名两次,并在进行更改时更改该值两次。你正在尝试的东西闻起来像是糟糕的设计,所以如果有其他方法,我会选择它。
发布于 2017-08-30 20:16:47
如果我没弄错你的问题,你不想使用@IBOutlet,但需要点击图片的名称。因此,您还可以将tag提供给UIImageView以识别它们,然后可以访问任何信息。
首先从情节提要中,将1或任何int值赋给tag属性,并检查User Interaction Enabled是否为ImageView。
将touchesEnded替换为以下行-
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch: UITouch = touches.first {
let location = touch.location(in: self.view)
if let touchedView = self.view.hitTest(location, with: event) as? UIImageView {
if touchedView.tag == 1 {
debugPrint(touchedView.image)
}
}
}
}希望能有所帮助。
https://stackoverflow.com/questions/45959826
复制相似问题