【问题标题】:Detect tap on specific part of UIButton检测对 UIButton 特定部分的点击
【发布时间】:2019-01-02 03:48:05
【问题描述】:

我正在开发一个 Instagram 克隆,我正在尝试处理用户与 Home Feed 屏幕中的照片标题功能的交互。

如果用户点击username,控制器将推送ProfileViewController,或者如果用户点击caption,控制器将推送CommentsViewController。 感谢您的任何建议!

【问题讨论】:

  • 所以你想要一个按钮根据按下按钮的位置导致不同的 IBActions?
  • 你可以关注this answer
  • @swiftcoder 是的,按钮或标签。我只是猜这个 Instagram 使用了一个带有不同 NSAttributed 的按钮,因为当我长按它时,它看起来非常接近,就像我在按钮上做的那样

标签: ios swift instagram


【解决方案1】:

您可以通过几种方式做到这一点。

您可以附加一个手势,如果您点击框架的特定部分,然后做一件事。

func tapMethod(gesture:UITapGestureRecognizer) {
    //on label
    let touch = tap.locationInView(button)
    If(label.frame.contains(touch)) {
        //....
    }
    //not on label
    Else {
        /....
    }
}

或者你可以添加2个点击手势,一个在标签上,一个在按钮上,然后你可以覆盖

func hitTest(_ point: CGPoint, 
    with event: UIEvent?) -> UIView?

这将允许您在必要时触摸按钮的子视图,并在必要时单击按钮的操作。这是一个很好的例子。 https://medium.com/@nguyenminhphuc/how-to-pass-ui-events-through-views-in-ios-c1be9ab1626b。它减少了代码的耦合,并允许不同的部分组合在一起。这是最难的路线,但在我看来,最大的好处是允许最简单的代码移动和流动

【讨论】:

    【解决方案2】:

    使用 label 的标签来查找哪个 label

    titleLabel.tag = 1
    captionLabel.tag = 2
    

    然后使用touchesBegan

        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    
        guard let touch = touches.first else { return }
        // to find cell index. use super view of label
    
        if let label = touch.view as! UILabel {
    
         if label.tag == 1 {
            // Move to profile screen
         } else if label.tag == 2 {
           // Move to comments screen
         }
        }
       }
    

    【讨论】:

      【解决方案3】:

      您可以在cellforRow 方法中为每个按钮分配标签,例如cell.button1.tag = 1 ...,并将 commonEvent 附加到您的 buttons 并检测哪个按钮被@点击987654323@等等..

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-12
        • 1970-01-01
        相关资源
        最近更新 更多