UIView touch event in controller

IosSwiftUiviewUiviewcontroller

Ios Problem Overview


How can I add UIView touchbegin action or touchend action programmatically as Xcode is not providing from Main.storyboard?

Ios Solutions


Solution 1 - Ios

You will have to add it through code. First, create the view and add it to the hierarchy:

var myView = UIView(frame: CGRectMake(100, 100, 100, 100))
self.view.addSubview(myView) 

After that initialize gesture recognizer. Until Swift 2:

let gesture = UITapGestureRecognizer(target: self, action: "someAction:")

After Swift 2:

let gesture = UITapGestureRecognizer(target: self, action:  #selector (self.someAction (_:)))

Then bind it to the view:

self.myView.addGestureRecognizer(gesture)

    

Swift 3:

func someAction(_ sender:UITapGestureRecognizer){     
  // do other task
}
    

Swift 4 just add @objc before func:

@objc func someAction(_ sender:UITapGestureRecognizer){     
    // do other task
}

Swift UI:

Text("Tap me!").tapAction {
    print("Tapped!")
}

Solution 2 - Ios

Swift 4 / 5:

let gesture = UITapGestureRecognizer(target: self, action:  #selector(self.checkAction))
self.myView.addGestureRecognizer(gesture)

@objc func checkAction(sender : UITapGestureRecognizer) {
    // Do what you want
}

Swift 3:

let gesture = UITapGestureRecognizer(target: self, action:  #selector(self.checkAction(sender:)))
self.myView.addGestureRecognizer(gesture)

func checkAction(sender : UITapGestureRecognizer) {
    // Do what you want
}

Solution 3 - Ios

Updating @Crashalot's answer for Swift 3.x:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self)
        // do something with your currentPoint
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self)
        // do something with your currentPoint
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self)
        // do something with your currentPoint
    }
}

Solution 4 - Ios

Updating @Chackle's answer for Swift 2.x:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.locationInView(self)
        // do something with your currentPoint
    }
}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.locationInView(self)
        // do something with your currentPoint
    }
}

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.locationInView(self)
        // do something with your currentPoint
    }
}

Solution 5 - Ios

Put this in your UIView subclass (it's easiest if you make a sublcass for this functionality).

class YourView: UIView {

  //Define your initialisers here

  override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    if let touch = touches.first as? UITouch {
      let currentPoint = touch.locationInView(self)
      // do something with your currentPoint
    }
  }

  override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
    if let touch = touches.first as? UITouch {
      let currentPoint = touch.locationInView(self)
      // do something with your currentPoint
    }
  }

  override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
    if let touch = touches.first as? UITouch {
      let currentPoint = touch.locationInView(self)
      // do something with your currentPoint
    }
  }
}

Solution 6 - Ios

For swift 4

@IBOutlet weak var someView: UIView!  
let gesture = UITapGestureRecognizer(target: self, action:  #selector (self.someAction (_:)))
self.someView.addGestureRecognizer(gesture)

@objc func someAction(_ sender:UITapGestureRecognizer){
    print("view was clicked")
}

Solution 7 - Ios

Create outlets from views that were created in StoryBoard.

@IBOutlet weak var redView: UIView!
@IBOutlet weak var orangeView: UIView!
@IBOutlet weak var greenView: UIView!   

Override the touchesBegan method. There are 2 options, everyone can determine which one is better for him.

  1. Detect touch in special view.

     override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
          if let touch = touches.first {
             if touch.view == self.redView {
                 tapOnredViewTapped()
             } else if touch.view == self.orangeView {
                 orangeViewTapped()
             } else if touch.view == self.greenView {
                 greenViewTapped()
             } else {
                 return
             }
         }
    
     }
     
    
  2. Detect touch point on special view.

     override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
         if let touch = touches.first {
             let location = touch.location(in: view)
             if redView.frame.contains(location) {
                 redViewTapped()
             } else if orangeView.frame.contains(location) {
                 orangeViewTapped()
             } else if greenView.frame.contains(location) {
                 greenViewTapped()
             }
         }
    
     }
    

Lastly, you need to declare the functions that will be called, depending on which view the user clicked.

func redViewTapped() {
    print("redViewTapped")
}

func orangeViewTapped() {
    print("orangeViewTapped")
}

func greenViewTapped() {
    print("greenViewTapped")
}

Solution 8 - Ios

You can use this way; create an extension.

extension UIView {
    
    func addTapGesture(action : @escaping ()->Void ){
        let tap = MyTapGestureRecognizer(target: self , action: #selector(self.handleTap(_:)))
        tap.action = action
        tap.numberOfTapsRequired = 1
        
        self.addGestureRecognizer(tap)
        self.isUserInteractionEnabled = true
        
    }
    @objc func handleTap(_ sender: MyTapGestureRecognizer) {
        sender.action!()
    }
}

class MyTapGestureRecognizer: UITapGestureRecognizer {
    var action : (()->Void)? = nil
}

and use this way:

@IBOutlet weak var testView: UIView!
testView.addTapGesture{
   // ...
}
    

Solution 9 - Ios

Swift 4.2:

@IBOutlet weak var viewLabel1: UIView!
@IBOutlet weak var viewLabel2: UIView!
  override func viewDidLoad() {
    super.viewDidLoad()

    let myView = UITapGestureRecognizer(target: self, action: #selector(someAction(_:)))
    self.viewLabel1.addGestureRecognizer(myView)
}

 @objc func someAction(_ sender:UITapGestureRecognizer){
   viewLabel2.isHidden = true
 }

Solution 10 - Ios

Just an update to above answers :

If you want to have see changes in the click event, i.e. Color of your UIVIew shud change whenever user clicks the UIView then make changes as below...

class ClickableUIView: UIView {
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
            if let touch = touches.first {
                let currentPoint = touch.locationInView(self)
                // do something with your currentPoint
            }
            
            self.backgroundColor = UIColor.magentaColor()//Color when UIView is clicked.
        }
        
        override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
            if let touch = touches.first {
                let currentPoint = touch.locationInView(self)
                // do something with your currentPoint
            }
            
            self.backgroundColor = UIColor.magentaColor()//Color when UIView is clicked.
        }
        
        override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
            if let touch = touches.first {
                let currentPoint = touch.locationInView(self)
                // do something with your currentPoint
            }
            
            self.backgroundColor = UIColor.whiteColor()//Color when UIView is not clicked.
        
}//class closes here

Also, call this Class from Storyboard & ViewController as:

@IBOutlet weak var panVerificationUIView:ClickableUIView!

Solution 11 - Ios

Updating @stevo.mit's answer for Swift 4.x:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self.view)
        // do something with your currentPoint
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self.view)
        // do something with your currentPoint
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self.view)
        // do something with your currentPoint
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiondhaval shahView Question on Stackoverflow
Solution 1 - IosMiknashView Answer on Stackoverflow
Solution 2 - IosventuzView Answer on Stackoverflow
Solution 3 - Iosstevo.mitView Answer on Stackoverflow
Solution 4 - IosCrashalotView Answer on Stackoverflow
Solution 5 - IosChackleView Answer on Stackoverflow
Solution 6 - IosDevB2FView Answer on Stackoverflow
Solution 7 - IosiAleksandrView Answer on Stackoverflow
Solution 8 - IosRasoul MiriView Answer on Stackoverflow
Solution 9 - IosHiền ĐỗView Answer on Stackoverflow
Solution 10 - IosPawanView Answer on Stackoverflow
Solution 11 - IosJacob AhlbergView Answer on Stackoverflow