[英]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.