iOS中的觸摸穿透hitTest


There is a requirement that can be scaled and moved in a common view in my project. But move the subview event, I need to implement touchesMoved:withEvent: method. So, the scale event was hijacked.This time we need to touch through.

Idea is very simple, we just need to tell the program which view to respond to events. This time we need hitTest:withEvent: method.

The function hitTest:withEvent: method is to find out what the view is under the touch point. Then according to our own logic to determine which view to respond to events.

views within views hierarchy, as follows:

Views Hierarchy

Put your finger inside D. Here's what will happen:

  1. hitTest:withEvent: is called on A, the top-most view of the view hierarchy.
  2. pointInside:withEvent: is called recursively on each view.
  3. pointInside:withEvent: is called on A, and returns YES.
  4. pointInside:withEvent: is called on B, and returns NO.
  5. pointInside:withEvent: is called on C, and returns YES.
  6. pointInside:withEvent: is called on D, and returns YES.
  7. On the views that returned YES, it will look down on the hierarchy to see the subview where the touch took place. In this case, from A, C and D, it will be D.
  8. D will be the hit-test view.

That's all.

Now, let's look at a simple demo.

The views hierarchy of storyboard, as follows:

Storyboard

The back view is my custom view, it is implementation as follows:

BackgroundView.swift

import Foundation
import UIKit

class BackgroundView: UIView {
    
    override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
        // Find out what the view is under the touch point 
        let hitView = super.hitTest(point, withEvent: event)
        
        // determine which view to respond to events
        if let customView = self.subviews.last as? CustomView {
            
            let movedViewPoint = customView.movedView.convertPoint(point, fromView: self)
            let moved2ViewPoint = customView.movedView2.convertPoint(point, fromView: self)
            
            if customView.movedView.pointInside(movedViewPoint, withEvent: event) {
                customView.userInteractionEnabled = true
                return customView.movedView
            } else if customView.movedView2.pointInside(moved2ViewPoint, withEvent: event) {
                customView.userInteractionEnabled = true
                return customView.movedView2
            }
        }
        
        return hitView;
    }
}

We need implement touchesMoved:withEvent: in custom view class.

CustomView.swift

import Foundation
import UIKit

class CustomView: UIView {
    
    var movedView: UIView!
    var movedView2: UIView!
    
    override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
        
        let hitView = super.hitTest(point, withEvent: event)
        if hitView != self.movedView {
        
            // Close user interaction, this time image view can be scaled
            self.userInteractionEnabled = false
        }
        
        return hitView
    }
    
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if let allTouches = event?.allTouches() {
            if let touch = (allTouches as NSSet).anyObject() {
                let optionView: UIView? = touch.view
                if optionView != nil {
                    if optionView!.tag < 101 {
                        return
                    }
                    let point = touch.locationInView(self)
                    optionView!.center = point
                }
            }
        }
    }
    
    func addMovedViewInView() {
        self.movedView = UIView(frame: CGRectMake(self.center.x, self.center.y, 100, 100))
        self.movedView.tag = 101
        self.movedView.layer.cornerRadius = 50.0
        self.movedView.backgroundColor = UIColor.blackColor()
        self.addSubview(self.movedView)
        
        self.movedView2 = UIView(frame: CGRectMake(50, 50, 100, 100))
        self.movedView2.tag = 102
        self.movedView2.layer.cornerRadius = 50.0
        self.movedView2.backgroundColor = UIColor.orangeColor()
        self.addSubview(self.movedView2)
    }
}

ViewController.swift

import UIKit

class ViewController: UIViewController, UIScrollViewDelegate {

    @IBOutlet weak var backView: BackgroundView!
    @IBOutlet weak var scrollView: UIScrollView!
    
    var imageView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.scrollView.delegate = self;
        self.scrollView.minimumZoomScale = 1.0;
        self.scrollView.maximumZoomScale = 3.0;
        self.scrollView.setZoomScale(self.scrollView.minimumZoomScale, animated: true)
        
        self.imageView = UIImageView(image: UIImage(named:"testImage"))
        self.imageView.frame = self.view.frame;
        self.scrollView.addSubview(self.imageView)
        
        let customView = CustomView(frame: UIScreen.mainScreen().bounds)
        customView.backgroundColor = UIColor.clearColor()
        customView.addMovedViewInView()
        self.backView.addSubview(customView)
    }
    
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return self.imageView
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

**Demo from github: **

Reference from:

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末捏鱼,一起剝皮案震驚了整個濱河市斗搞,隨后出現(xiàn)的幾起案子摘符,更是在濱河造成了極大的恐慌,老刑警劉巖躏结,帶你破解...
    沈念sama閱讀 212,080評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異践磅,居然都是意外死亡按傅,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,422評論 3 385
  • 文/潘曉璐 我一進店門服协,熙熙樓的掌柜王于貴愁眉苦臉地迎上來绍昂,“玉大人,你說我怎么就攤上這事偿荷【接危” “怎么了?”我有些...
    開封第一講書人閱讀 157,630評論 0 348
  • 文/不壞的土叔 我叫張陵跳纳,是天一觀的道長忍饰。 經(jīng)常有香客問我,道長寺庄,這世上最難降的妖魔是什么艾蓝? 我笑而不...
    開封第一講書人閱讀 56,554評論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮斗塘,結(jié)果婚禮上赢织,老公的妹妹穿的比我還像新娘。我一直安慰自己馍盟,他們只是感情好于置,可當我...
    茶點故事閱讀 65,662評論 6 386
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著贞岭,像睡著了一般八毯。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上瞄桨,一...
    開封第一講書人閱讀 49,856評論 1 290
  • 那天话速,我揣著相機與錄音,去河邊找鬼芯侥。 笑死尿孔,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的筹麸。 我是一名探鬼主播活合,決...
    沈念sama閱讀 39,014評論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼物赶!你這毒婦竟也來了白指?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,752評論 0 268
  • 序言:老撾萬榮一對情侶失蹤酵紫,失蹤者是張志新(化名)和其女友劉穎告嘲,沒想到半個月后错维,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,212評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡橄唬,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,541評論 2 327
  • 正文 我和宋清朗相戀三年赋焕,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片仰楚。...
    茶點故事閱讀 38,687評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡隆判,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出僧界,到底是詐尸還是另有隱情侨嘀,我是刑警寧澤,帶...
    沈念sama閱讀 34,347評論 4 331
  • 正文 年R本政府宣布捂襟,位于F島的核電站咬腕,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏葬荷。R本人自食惡果不足惜涨共,卻給世界環(huán)境...
    茶點故事閱讀 39,973評論 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望宠漩。 院中可真熱鬧煞赢,春花似錦、人聲如沸哄孤。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,777評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽瘦陈。三九已至,卻和暖如春波俄,著一層夾襖步出監(jiān)牢的瞬間晨逝,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,006評論 1 266
  • 我被黑心中介騙來泰國打工懦铺, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留捉貌,地道東北人。 一個月前我還...
    沈念sama閱讀 46,406評論 2 360
  • 正文 我出身青樓冬念,卻偏偏與公主長得像趁窃,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子急前,可洞房花燭夜當晚...
    茶點故事閱讀 43,576評論 2 349

推薦閱讀更多精彩內(nèi)容