简体   繁体   English

自定义UIView addTarget?

[英]Custom UIView addTarget?

I am creating a custom UIView . 我正在创建一个自定义UIView I am wondering how can I replicate the UIButton behavior on this UIView . 我想知道如何在此UIView上复制UIButton行为。

I would like to be able to call addTarget to it like an UIButton . 我希望能够像UIButton一样调用addTarget

I know that I can subclass UIControl and call 我知道我可以UIControl并调用

self.sendActionsForControlEvents(UIControlEvents.TouchUpInside);

but I would like to do it on an UIView since I am designing it on a XIB file. 但我想在UIView上进行操作,因为我是在XIB文件上进行设计的。

There is an easy way to achieve this. 有一个简单的方法可以实现此目的。

  1. Go to Interface builder of your class 转到您班级的“界面”构建器
  2. Select the view u want to add action 选择您要添加操作的视图
  3. open IDENTITY INSPECTOR, change class from UIView to 'UIControl'. 打开IDENTITY INSPECTOR,将类从UIView更改为“ UIControl”。

Now u can add any IBAction method to this view. 现在,您可以向该视图添加任何IBAction方法。

Its working like charm. 它的运作就像魅力。 happy coding. 快乐的编码。 hope it may help 希望对您有所帮助

Update 更新资料

its working in xCode 10.1 and swift 4+ 它可以在xCode 10.1和Swift 4+中运行

This will be better if we talking about swift3 or swift 4 如果我们谈论swift3或swift 4会更好

let gesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(targetViewDidTapped))
gesture.numberOfTapsRequired = 1
targetView?.isUserInteractionEnabled = true
targetView?.addGestureRecognizer(gesture)

you can use UITapGestureRecognizer , add it on view programmatically as follows 您可以使用UITapGestureRecognizer ,通过编程将其添加到视图中,如下所示

self.userInteractionEnabled = true
let gesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
gesture.numberOfTapsRequired = 1
self.addGestureRecognizer(gesture)

and implement the selector, You can also add gesture to view using xib or Interface Builder file. 并实现选择器,还可以添加手势以使用xib或Interface Builder文件进行查看。

In Swift 4 there is new syntax of init UITapGestureRecognizer : 在Swift 4中,有一个新的init UITapGestureRecognizer语法:

let gesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("viewTapped:"))
// or declare like this
let gesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(YourClass.viewTapped(gesture:)))
yourView.addGestureRecognizer(gesture)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM