1

I'm developing an instagram clone and I'm trying to dealing with user interact with a photo caption feature in Home Feed screen. example

I want if a user tap on username, controller will push ProfileViewController or if user tap on caption, controller will push CommentsViewController. Thanks for any suggest!

andesta.erfan
  • 924
  • 1
  • 14
  • 30
Tung Vu Duc
  • 1,414
  • 1
  • 12
  • 20
  • https://stackoverflow.com/questions/1256887/create-tap-able-links-in-the-nsattributedstring-of-a-uilabel/28519273#28519273 – Dixit Akabari Jan 02 '19 at 04:40
  • So you want to have one button that causes different IBActions depending on where the button is pressed? –  Jan 02 '19 at 04:40
  • 1
    https://samwize.com/2016/03/04/how-to-create-multiple-tappable-links-in-a-uilabel/ – Dixit Akabari Jan 02 '19 at 04:41
  • You can follow [this answer](https://stackoverflow.com/a/21577829/1140335) – TheTiger Jan 02 '19 at 04:56
  • @swiftcoder yes, button or label. I just guess that instagram using a button with differents NSAttributed because when I long press on it, it looks pretty close like when I do on button – Tung Vu Duc Jan 02 '19 at 05:42

3 Answers3

1

You can do this a few ways.

You can attach a gesture and if you tap on a specific part of the frame, then do one thing.

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

Or you can add 2 tap gestures, one on the label and one on the button, then you can override

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

This will allow you to touch on the button’s subviews if necessary as well click on the button’s actions if necessary. Here is a good example. https://medium.com/@nguyenminhphuc/how-to-pass-ui-events-through-views-in-ios-c1be9ab1626b. It reduces the coupling of code and allows for different pieces to come together. This is the hardest route but in my opinion, has the greatest benefit of allowing easiest movement and flow of code

impression7vx
  • 1,743
  • 1
  • 16
  • 44
0

Use tag of label to find which label

titleLabel.tag = 1
captionLabel.tag = 2

then use 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
     }
    }
   }
Kathiresan Murugan
  • 2,443
  • 3
  • 22
  • 39
0

you can assign tags to each of your buttons in cellforRow Method like cell.button1.tag = 1 ... and attach a commonEvent to your buttons and detect which button is tapped by sender.tag == 1 { } and so on ..

Kathiresan Murugan
  • 2,443
  • 3
  • 22
  • 39