【问题标题】:UIView with label + button - Tap gesture not recognized带有标签+按钮的 UIView - 无法识别点击手势
【发布时间】:2018-03-13 21:16:09
【问题描述】:

我在导航项标题视图中添加了一个标签和一个图像,就像这样 - https://stackoverflow.com/a/38548905/1373592

我添加了这三行代码,使标题可点击。

    ....
    let recognizer = UITapGestureRecognizer(target: self, action: #selector(MyViewController.titleTapped(_:)))
    navView.isUserInteractionEnabled = true
    navView.addGestureRecognizer(recognizer)

还有这个titleTapped函数。

    @objc func titleTapped(_ tapGestureRecognizer: UITapGestureRecognizer) {
        print("Tapped")
    }

我做错了什么?

我尝试将手势识别器添加到标签和图像(分别)。那也没用。

谢谢。

【问题讨论】:

  • 你在标签上设置userInteractionEnabled了吗?
  • 你的NavView 没有框架...如果你给它一个背景颜色,你会发现它没有出现。如果您设置navView.clipsToBounds = true,您将看不到您的标签或图像。您需要给NavView 一个框架,并设置标签和图像相对于该框架的大小和位置。

标签: ios swift uigesturerecognizer


【解决方案1】:

您的NavView 没有框架,因此没有“那里”可以点击。

添加这一行:

    // Create a navView to add to the navigation bar
    let navView = UIView()

    // new line
    navView.frame = CGRect(x: 0, y: 0, width: 200, height: 40)

    // Create the label
    let label = UILabel()

你应该在路上了。

【讨论】:

    【解决方案2】:

    100% 确定可以在我的应用中运行并经过良好测试。

     var tapGesture = UITapGestureRecognizer()
    

    采取您的观点并将 IBOutlet 设置为:

    @IBOutlet weak var viewTap: UIView!     
    

    在 viewDidLoad() 上编写漂亮的代码,例如:

    tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.myviewTapped(_:)))
    tapGesture.numberOfTapsRequired = 1
    tapGesture.numberOfTouchesRequired = 1
    viewTap.addGestureRecognizer(tapGesture)
    viewTap.isUserInteractionEnabled = true
    

    当点击手势识别时调用此方法

     @objc func myviewTapped(_ sender: UITapGestureRecognizer) {
    
    if self.viewTap.backgroundColor == UIColor.yellow {
        self.viewTap.backgroundColor = UIColor.green
    }else{
        self.viewTap.backgroundColor = UIColor.yellow
    }
    }
    

    注意:在您的情况下,您必须确定要查看哪个视图,例如 UILabel 或 UIView 是导航,然后将手势分配给它。如果您的标签覆盖整个视图,那么让我们尝试仅对标签进行手势。

    【讨论】:

    • OP 将视图用作 NavigationBar 中的 .titleView ......您的回答根本没有解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 2013-10-13
    • 1970-01-01
    • 2023-03-12
    相关资源
    最近更新 更多