【问题标题】:Swift 2.2 – how to call touchesShouldCancelInContentView for UIButton nested in UIView?Swift 2.2 – 如何为嵌套在 UIView 中的 UIButton 调用 touchesShouldCancelInContentView?
【发布时间】:2016-12-23 03:28:39
【问题描述】:

所以我有一个包含 UIScrollviewUIView。滚动视图内部是一个 UIViews 数组,每个都包含一个 UILabel 和一个 UIButton。我想让它在滚动视图内的视图内触摸然后拖动按钮仍会滚动,因为默认情况下并非如此。

我对 iOS 编程还很陌生,所以这可能是一个愚蠢的问题,请原谅。

【问题讨论】:

    标签: ios swift uiview uiscrollview uibutton


    【解决方案1】:

    事实证明这很容易。我从这个问题的一个答案中得到了答案:UIButton touch is delayed when in UIScrollView

    您需要做的是子类化您的 UIScrollview,然后粘贴以下代码:

    override func touchesShouldCancelInContentView(view: UIView) -> Bool {
    
        if view is UIButton {
            return  true
        }
    
        return  super.touchesShouldCancelInContentView(view)
    }
    

    重要提示:您需要让您的内容触摸可取消,并且“延迟内容触摸”需要为 false。您可以通过将 scrollview.delaysContentTouches 设置为 false 在代码中或在 Interface Builder 中的 Scrollview 属性中执行此操作:

    【讨论】:

      【解决方案2】:

      我在表格单元格内的容器视图中嵌入了按钮和标签时​​遇到了类似的问题。按钮正在拦截触摸事件。

      如果您不需要按钮在按下时突出显示,那么我所做的就是使用 UIView 和点击 手势识别器 而不是按钮。

      let fakeButtonView = UIView()
      fakeButtonView.translatesAutoresizingMaskIntoConstraints = false
      fakeButtonView.backgroundColor = UIColor.whiteColor()
      
      let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(buttonTapped))
      fakeButtonView.addGestureRecognizer(gestureRecognizer)
      
      let label = UILabel()
      label.translatesAutoresizingMaskIntoConstraints = false
      label.text = ...
      label.numberOfLines = 1
      label.textAlignment = .Center
      label.lineBreakMode = .ByTruncatingTail
      label.minimumScaleFactor = 0.5
      label.font = UIFont.systemFontOfSize(17.0)
      
      fakeButtonView.addSubview(label)
      fakeButtonView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-5-[label]-5-|",
      options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["label": label]))
      fakeButtonView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[label]|",
      options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["label": label]))
      
      container.addSubview(fakeButtonView)
      
      // Constraints from button to container
      //
      // ...
      

      【讨论】:

      • 谢谢,我可能最终会使用它,但我正试图弄清楚如何具体实现 touchesShouldCancelInContentView。我认为学习可能会帮助我处理其他事情。
      • 如果您仍然感兴趣,请查看我刚刚发布的答案——我想出了如何以一种非常简单的方式做到这一点。更少的代码,我仍然可以使用按钮状态?
      • 谢谢,有机会我试试。按钮状态绝对是一个奖励!
      猜你喜欢
      • 2012-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-10
      • 2016-02-05
      • 2018-01-19
      • 2019-08-09
      相关资源
      最近更新 更多