[英]How to add gesture recognizer to custom UIView (XIB) programmatically?
我试图将点击识别器添加到我的自定义UIView
类CardView
的实例中。 所以我创建了一个自定义视图xib
并通过File's Owner
链接我的 Swift 类文件CardView.swift
。 之后,我将每个插座连接到相应的 UI 元素。
我想以编程方式将我的自定义视图CardView
添加到我的 ViewController 并将 tapGesture 附加到新创建的视图。
class CardView: UIView {
// Delcare outlets
@IBOutlet var view: UIView!
@IBOutlet weak var title: UILabel!
@IBOutlet weak var icon: UIImageView!
//MARK: Initialization
override init(frame: CGRect) {
super.init(frame: frame)
Bundle.main.loadNibNamed("CardView", owner: self, options: nil)
addSubview(view)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
}
在 ViewController.swift 的viewDidLoad()
函数中,我创建了一个 CardView() 实例:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let cardView = CardView()
self.view.addSubview(cardView)
// Style cardView instance
cardView.view.backgroundColor = UIColor.yellow
cardView.view.center.x = self.view.center.x
cardView.view.center.y = self.view.center.y
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(gestureRecognizer:)))
cardView.addGestureRecognizer(tapGesture)
}
然后我像往常一样使用 Swift 将 tapGesture 添加到我的cardView
:
let tapGesture = UIPanGestureRecognizer(target: self, action: #selector(handleTap(gestureRecognizer:))) cardView.addGestureRecognizer(panGesture)
并添加相应的要调用的函数:
func handleTap(gestureRecognizer: UIGestureRecognizer) {
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
我在向新创建的 CardView(CardView 的一个实例)添加点击手势识别器时遇到的问题是函数handleTap()
从未被调用。
我已经尝试了几种方法,例如向两个文件( ViewController.swift
和CardView.swift
类)添加cardView.isUserInteractionEnabled = true
。 还要添加这些文件之一,而不是另一个。
声明手势类型后,我还尝试将其添加到超级视图中,即与ViewController.swift file
链接的视图。 当我点击屏幕时,将触发该功能,但不会触发我自己创建的自定义 UIView。
除了这些,我还尝试将UIGestureRecognizerDelegate
添加到我的 VC 类中,但没有结果。
class ViewController: UIViewController, UIGestureRecognizerDelegate {}
在我将手势连接到我的cardView
之前的viewDidLoad()
函数中,我添加了以下额外的行: tapGesture.delegate = self
。
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(gestureRecognizer:)))
tapGesture.delegate = self
architectView.addGestureRecognizer(tapGesture)
我对自定义 UIView 有同样的问题。
我制作了Xib和swift文件并连接了它。 然后给 UIView 添加手势,但是,它不起作用。 我将 UIView 更改为 UIButton 以解决问题但不起作用。
解决我的问题是
当我运行应用程序并通过Debug view hierarchy进行调试时,我的 customUIView 存在不明确的问题。
通过 UIView 的打印描述,我可以通知它有 frame(0,0),另一方面 subView 有自己的 frame。
所以我从头开始删除和制作,每次运行测试并解决它。 单击自定义 UIView 时,手势功能也有效。
我希望这对你有用。 我看到了您的代码,您的代码似乎没有问题,因此请检查 xib 文件并自动布局这些标签和图像。
更正UIPanGestureRecognizer(target: self, action: #selector(dragged))
与
UIPanGestureRecognizer(target: self, action: #selector(dragged(sender:)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.