相關(guān)方法如下:
- (CGPoint)convertPoint:(CGPoint)point toView:(nullable UIView *)view;
- (CGPoint)convertPoint:(CGPoint)point fromView:(nullable UIView *)view;
- (CGRect)convertRect:(CGRect)rect toView:(nullable UIView *)view;
- (CGRect)convertRect:(CGRect)rect fromView:(nullable UIView *)view;
判讀兩個(gè)控件是否有重疊
一.當(dāng)兩個(gè)控件共用一個(gè)父控件的時(shí)候,直接通過如下示例判斷
CGRectIntersectsRect(view1.frame, view2.frame)
判斷的2個(gè)函數(shù)如下
- bool CGRectContainsRect(CGRect rect1, CGRect rect2)
- 判斷rect1是否包含了rect2
- bool CGRectIntersectsRect(CGRect rect1, CGRect rect2)
- 判斷rect1和rect2是否有重疊
注意:rect1和rect2要在同一個(gè)坐標(biāo)系,比較結(jié)果才準(zhǔn)確
二.當(dāng)兩個(gè)控件父控件不相同的時(shí)候
需要先將兩個(gè)控件矩形框轉(zhuǎn)換到同一個(gè)坐標(biāo)原點(diǎn)下,再將轉(zhuǎn)換后的矩形框傳到如下方法中:
CGRectIntersectsRect(rect1, rect2)
轉(zhuǎn)換坐標(biāo)系相關(guān)方法總結(jié)
view2坐標(biāo)系 : 以view2的左上角為坐標(biāo)原點(diǎn)
view1坐標(biāo)系 : 以view1的左上角為坐標(biāo)原點(diǎn)
CGRect newRect = [view1 convertRect:rect fromView:view2];
// 讓rect這個(gè)矩形框, 從view2坐標(biāo)系轉(zhuǎn)換到view1坐標(biāo)系, 得出一個(gè)新的矩形框newRect
// rect和view2的含義 : 用來確定矩形框原來在哪
CGRect newRect = [view1 convertRect:rect toView:view2];
// 讓rect這個(gè)矩形框, 從view1坐標(biāo)系轉(zhuǎn)換到view2坐標(biāo)系, 得出一個(gè)新的矩形框newRect
// rect和view1的含義 :用來確定矩形框原來在哪
獲得一個(gè)控件在window中的位置和尺寸
- 以獲得redView在window中的位置和尺寸為例
CGRect newRect = [[UIApplication sharedApplication].keyWindow convertRect:redView.bounds fromView:redView];
CGRect newRect = [[UIApplication sharedApplication].keyWindow convertRect:redView.frame fromView:redView.superview];
CGRect newRect = [redView convertRect:redView.bounds toView:[UIApplication sharedApplication].keyWindow];
CGRect newRect = [redView.superview convertRect:redView.frame toView:[UIApplication sharedApplication].keyWindow];
CGRect newRect = [redView convertRect:redView.bounds toView:nil];
CGRect newRect = [redView.superview convertRect:redView.frame toView:nil];