2017-08-30 79 views
1

在我的故事板中,我有几个图像为“启用了用户交互”。 在UIViewController我重写touchesEnded函数。从touches获取图像名称已结束

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { 
     super.touchesEnded(touches, with: event) 
} 

是否有可能让我得到在这个函数中点击的图像的名称?我宁愿不要@IBOutlet的图像。

+0

你能解释为什么你不喜欢使用IBOutlet的图像?视图是动态还是布局每次显示都一样? – Stephen

+0

@stephen它是一个堆栈视图中的静态图像和动态图像的混合。 –

+0

检查此答案:https://stackoverflow.com/a/5192999/1718685您应该能够确定触摸下方的视图。 – Stephen

回答

0

我相当肯定,这是不可能的,就像你想要的一样。图像视图不保留它们加载图像的文件,仅保留图像数据本身。但我假设你在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) 
    } 
} 

注意,如果你想这样做,这样,你必须设置图像文件名称两次,并进行更改时更改值的两倍。你正在尝试什么味道不好的设计,所以如果有另一种方式我会去做。

+0

我如何检索touchesEnded中的恢复ID? –

+0

@DanielÅsberg检查我的编辑 – kevin

0

如果我的问题得到了解决,您不想使用@IBOutlet,但需要获取点击图片的名称。因此,您也可以通过tagUIImageView来识别它们,然后可以访问任何信息。

第一从故事板,分配1或任何int值tag属性并检查User Interaction EnabledImageView

有以下线 -

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) 
       } 
      } 
     } 
    } 

希望它可以帮助更换touchesEnded。

+0

你是什么意思提到**请不要downvote它**。在答案中不允许提及这种类型的metnion。如果你不确定你的答案,那么只需添加评论。 –

+0

我会如何在touchesEnded中检索该标签? –

+0

@NitinGohel我在这里是新来的,所以不太了解,我会添加提交,但它需要50点声望。 – Maanu