Search code examples
iosswiftuiviewcontrollertouchesended

How to detect if iOS UIViewController is being interacted with or touched


I have a specific UIViewController for which I want to block the idleTimer processing done by iOS. I know that I can set: UIApplication.shared.isIdleTimerDisabled = true However, I want to be able to set a timer to re-enable the normal system idle timer processing after a fixed amount of time, thus I can keep the screen on for a minimum amount of time. The nature of the app is such that you would have a view open and use it for reference/reading for a longish time.

The KEY POINT is that I want the timer to restart every time the user touches the screen or interacts with the device. So I need to be able to detect if the user does anything so I can rest the time.

I tried to override the touchesEnded method in the controller, however testing showed that the method is never called. Any ideas would be welcomed (in swift 3:)


Solution

  • Swift 3.0 :-

    Need to detect touch of the particular view without IBOutlet, then select that particular UIView then goto Attributes Inspector -> View -> tag and set Integer as tag whatever need.

    enter image description here

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    
        let touch = touches.first
    
        let tag = touch?.view?.tag
        if tag == 1{
            //Do More....
        }else{
        //......
        }
    
    }
    

    If you need to check with IBOutlet, then do like as below.

    Here, @IBOutlet var diamondView: UIView!

    if touch?.view == self.diamondView{
    
        //Do More....
    }else{
    //......
    }
    

    Update : Scroll View

    If you need to detect touch of the scroll view then use UITapGestureRecognizer. By story board drag and drop to to of the UIViewController and set delegate and gestureRecognizers for scroll view to UITapGestureRecognizer. After that just create action for UITapGestureRecognizer like as below screenshot. enter image description here

    Adding UITapGesture Programmatically :-

    Also below code works fine without do like above screenshot.

    @IBOutlet var scrollView: UIScrollView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.actionTapOnScrollView(sender:)))
        self.scrollView.addGestureRecognizer(tapGesture)
    
    
    }
    
    @objc private func actionTapOnScrollView(sender:UITapGestureRecognizer){
        print("user Touched")
    }